Sub topic 9
Stop Words: What to Remove and Why
This chapter assumes you can write Python functions and comprehensions. It also assumes you know what a token is, and that you have seen the earlier steps of this pipeline: Unicode normalisation with unicodedata.normalize and case folding with str.casefold(). Here we deal with the last filtering step, removing stop words, and the mistakes that make it silently fail.
What stop words are
A stop word is a very common word that carries little topical meaning on its own. In English the usual examples are "the", "a", "of", "is", and "and". They make up a large share of the tokens in almost any text, but they rarely tell you what a document is about.
Removing them has three practical effects:
- Smaller data. Fewer tokens means smaller indexes, vocabularies, and feature matrices.
- Less noise in count-based methods. Bag-of-words counts, TF-IDF weights, word clouds, and topic models are dominated by frequent words unless you filter them or down-weight them.
- Cleaner keywords. Keyword extraction and term-frequency summaries look more useful when "the" is not the top term.
The risks are just as real. A stop word list is a blunt tool: it deletes words by identity, whatever role they play in a sentence. "not" is a stop word in many lists, and deleting it reverses the meaning of a review. The sections below cover how to apply a list correctly and when to leave it out.
A stop list is a set of strings in some normal form
Filtering is a membership test: is this token in the list? That test is an exact string comparison, so it has the same problems as every other comparison in this tutorial. If the text has been case folded and the list has not, the test fails without any error.
tokens = ["the", "caf\u00e9", "is", "open"]
raw_list = {"The", "Is"}
print([t for t in tokens if t not in raw_list])
# ['the', 'café', 'is', 'open'] nothing was removedThe fix is to put the list through the same normalisation function as the text. Build the list once, at load time:
import re
import unicodedata
def normalise(text):
text = unicodedata.normalize("NFKC", text)
text = text.replace("\u2019", "'") # curly apostrophe to straight
text = text.casefold()
return re.sub(r"\s+", " ", text).strip()
def build_stop_words(words):
return {normalise(w) for w in words}
def tokenise(text):
return re.findall(r"\w+(?:'\w+)*", text)
def remove_stop_words(tokens, stop_words):
return [t for t in tokens if t not in stop_words]
english = build_stop_words(["The", "Is", "A", "Of"])
tokens = tokenise(normalise("The Caf\u00e9 is open"))
print(tokens) # ['the', 'café', 'is', 'open']
print(remove_stop_words(tokens, english)) # ['café', 'open']Two details matter here. First, normalise includes casefold, not lower. Second, the stop list is stored in a set, so each membership test takes roughly constant time. A list works for a few words, but a set is the habit to keep, because a corpus has millions of tokens.
Case folding catches variants that lowercasing misses
German has two spellings of the conjunction "that": the current "dass" and the older "daß". Under casefold(), "daß" becomes "dass", and "DASS" becomes "dass". A list that contains either spelling matches both once it has been normalised:
import re
import unicodedata
def normalise(text):
return unicodedata.normalize("NFKC", text).casefold()
german = {normalise(w) for w in ["und", "da\u00df", "der"]}
text = "Er sagt, DASS der Hund bellt"
tokens = re.findall(r"\w+", normalise(text))
print(tokens) # ['er', 'sagt', 'dass', 'der', 'hund', 'bellt']
print([t for t in tokens if t not in german]) # ['er', 'sagt', 'hund', 'bellt']If you skipped normalising the list, "daß" would stay in it as written, and the token "dass" would pass through the filter.
Tokenise first, then filter
Stop words are words, so you can only match them after the text has been split into tokens. Filtering raw text with str.replace(" the ", " ") fails at the start and end of a string, next to punctuation, and across tabs and newlines. It also corrupts longer words if you leave out the spaces.
The tokeniser decides what counts as a word, and that decision interacts with the list. Consider contractions:
import re
print(re.findall(r"\w+", "i don't like it"))
# ['i', 'don', 't', 'like', 'it']
print(re.findall(r"\w+(?:'\w+)*", "i don't like it"))
# ['i', "don't", 'like', 'it']The simple pattern \w+ splits "don't" into "don" and "t". Neither piece is likely to be on your list, and "t" becomes a junk token. The second pattern keeps the contraction whole, so a list entry like "don't" can match it.
A related trap is the apostrophe character. Typeset text often uses the curly apostrophe (U+2019) instead of the straight one. NFKC does not convert it, so "don’t" and "don't" are different strings. The normalise function above replaces the curly apostrophe before tokenising, which keeps both forms matching the same list entry.
Tokenisers in libraries make their own choices. If your list says "don't" but your tokeniser emits "do" and "n't", the entry never fires. Whatever tokeniser you use, check that its output forms appear in your list.
Lists differ, and you should read yours
There is no standard English stop word list. NLTK, spaCy, and scikit-learn each ship their own, and they differ in length and content. Some include "not" and "no". Some include words like "move" or "bill" that have clear meaning. Lists also differ by language, and a list for one language is wrong for another: the Spanish "me" and the English "me" share a spelling but only one of them belongs in each list.
Before you adopt a list, do three things:
- Print it and read it.
- Check whether it contains negations, modal verbs ("can", "should"), or words that matter in your domain.
- Normalise it with your own
normalisefunction, as shown above.
Treat the list as a configuration file for your project, not as a fixed fact about the language.
Words that look unimportant but carry meaning
The standard failure is negation. Here is the same sentence filtered with and without protection:
STOP_WORDS = {"i", "it", "the", "is", "this", "was", "very", "not", "no", "don't"}
KEEP = {"not", "no", "don't"}
def remove_stop_words(tokens, stop_words, keep=frozenset()):
active = stop_words - keep
return [t for t in tokens if t not in active]
tokens = ["this", "movie", "is", "not", "good"]
print(remove_stop_words(tokens, STOP_WORDS))
# ['movie', 'good']
print(remove_stop_words(tokens, STOP_WORDS, keep=KEEP))
# ['movie', 'not', 'good']
tokens = ["i", "don't", "like", "it"]
print(remove_stop_words(tokens, STOP_WORDS, keep=KEEP))
# ["don't", 'like']Without keep, "this movie is not good" becomes "movie good", which a sentiment classifier reads as praise. Subtracting a protected set from the list is a cheap and explicit way to fix this, and it documents your decision in the code.
Other cases where common words matter:
- Names. "Bank of America", "The Hague", and "Who" (the band) lose part of their identity when "of", "the", and "who" are deleted.
- Phrases. "To be or not to be" consists only of stop words in many lists, so the whole query disappears.
- Short documents. In a tweet or a search query, a single deleted word is a large fraction of the content.
- Grammar-sensitive tasks. Part-of-speech tagging, parsing, and translation need the function words.
Stop words depend on the corpus
A word that is empty in one domain can be informative in another, and a domain often has its own near-stop words. In legal text, "court" appears in almost every document and helps little to tell documents apart. One way to find such words is document frequency, the fraction of documents that contain a term:
from collections import Counter
def frequent_terms(docs, threshold=0.8):
doc_freq = Counter()
for doc in docs:
doc_freq.update(set(doc))
return {term for term, n in doc_freq.items() if n / len(docs) >= threshold}
docs = [
["the", "court", "held", "the", "claim", "valid"],
["the", "court", "dismissed", "the", "appeal"],
["court", "upheld", "the", "ruling"],
["the", "court", "denied", "the", "motion"],
["a", "court", "reviewed", "the", "claim"],
]
print(sorted(frequent_terms(docs))) # ['court', 'the']Both "the" and "court" appear in every document. The result is a candidate list, not a verdict. Read it before using it, because a high document frequency does not prove that a word is uninformative. Tools like TF-IDF reach a similar effect more smoothly, by down-weighting common terms instead of deleting them.
Where stop word removal sits in the pipeline
Stop word removal comes after normalisation and tokenisation, because it needs tokens in the same form as the list. It also comes before steps like building a vocabulary or computing counts, because deleting words afterwards leaves stale entries.
Two ordering rules need care:
- Stemming or lemmatisation. If you reduce words to stems first, a stem like "us" (from "using") might match the stop word "us". Filter before stemming, or keep a separate list of stems.
- Accent stripping. If you strip accents from the text, strip them from the list as well. French "été" becomes "ete", and a list entry that still has the accents never matches.
Deciding whether to remove them
The right choice depends on what the next step does with the tokens. Use this table as a starting point and test it on your own data.
| Task | Remove stop words? | Reason |
|---|---|---|
| Topic modelling, keyword extraction | Usually yes | Frequent function words swamp the topics. |
| Bag-of-words classification with TF-IDF | Often optional | TF-IDF already down-weights common words. |
| Sentiment analysis | Only with protection | Negations and intensifiers change polarity. |
| Named entity recognition | No | Names contain function words, and models use context. |
| Phrase search and exact queries | No | Phrases like "to be or not to be" depend on them. |
| Pretrained transformer models | No | They were trained on full text and use word order. |
When you are unsure, run the task both ways and compare a metric such as accuracy or retrieval quality. Removing stop words is an experiment, not a default.
Common errors
- Raw list, normalised text. Fix: run the list through
normaliseonce at load time. - Wrong tokeniser for the list. Fix: print the tokens for a sentence with contractions and check that list entries can match them.
- Deleting negations. Fix: subtract a protected set from the list for sentiment tasks.
- Using one list for every language. Fix: pick a list per language and detect the language first if the corpus is mixed.
- Filtering after stemming. Fix: filter first, or normalise the list the same way as the tokens.
Exercise
You build a list with {"The", "And"} and run [t for t in tokens if t not in stop_words] on tokens produced by normalise(text), which uses casefold(). Nothing is removed. Why, and what is the smallest fix?
Show answer
The tokens are lowercase ("the", "and"), but the list holds "The" and "And", so the membership test never matches. The fix is to build the list with the same function, for example stop_words = {normalise(w) for w in ["The", "And"]}.
Exercise
Using remove_stop_words(tokens, stop_words, keep) from this chapter, what does it return for tokens = ["it", "was", "not", "very", "good"], stop_words = {"it", "was", "not", "very"}, and keep = {"not", "very"}? Why might you protect "very" as well as "not" in a sentiment task?
Show answer
It returns ['not', 'very', 'good']. The function removes "it" and "was" and keeps the two protected words. "very" is an intensifier, so "very good" is stronger than "good", and the two protected words together keep the polarity and the strength that a sentiment model can use.