Sub topic 3
Tokenising before filtering
This chapter assumes you know basic Python: strings, lists, list comprehensions, and functions. It also assumes you know that a token is one unit of text, usually a word, and that text is stored as bytes in an encoding such as UTF-8.
Tokenising before filtering
Stop word removal compares whole words against a list, so the text must first be split into tokens. If you filter the raw string instead, punctuation and spacing break the match. The string "the," does not equal "the", so the word is kept.
Stop words: what to remove and why
Stop words are common words such as "the", "is", and "in". They add little meaning for many tasks. The stop word list must use the same normalised form as the text. If the text is casefolded, a list entry of "The" never matches.
import re
import unicodedata
STOP_WORDS = {"the", "a", "an", "is", "of", "and", "to", "in"}
def normalise(text):
text = unicodedata.normalize("NFKC", text)
text = text.casefold()
return re.sub(r"\s+", " ", text).strip()
def tokenise(text):
return re.findall(r"\w+", text)
def remove_stop_words(tokens):
return [t for t in tokens if t not in STOP_WORDS]
raw = "The Caf\u00e9 is in the \ufb01eld"
tokens = tokenise(normalise(raw))
print(tokens) # ['the', 'café', 'is', 'in', 'the', 'field']
print(remove_stop_words(tokens)) # ['café', 'field']Putting the steps in the right order
Each step should receive the form that the next step expects. Normalise before tokenising, so the tokeniser sees clean text. Casefold before removing stop words, so "The" and "the" both match. Strip accents only after you know whether the stop word list contains accented words.
When not to clean: trade-offs by task
Cleaning discards information, so choose steps by task. Sentiment analysis needs negations such as "not" and punctuation such as "!", so removing stop words can flip the meaning. Named entity recognition uses capitals to find names, so casefolding can hurt it. Search can keep stop words in phrases such as "to be or not to be".
Exercise
If you call removestopwords on tokens from raw text without normalising it, why does "The" survive the filter?
Show answer
The stop word list holds "the" in lowercase, and "The" is a different string. Normalising with casefold first makes the token "the", which matches the list.