Sub topic 8
Tokenising before filtering
This chapter covers the step between normalisation and stop word removal: splitting text into tokens. I assume you have read the earlier chapters on case folding and Unicode normalisation. I also assume you are comfortable with Python regular expressions, list comprehensions, and sets.
Why filtering needs tokens
Stop word removal asks a yes/no question about each word: "is this word in my list?" That question only makes sense once the text has been split into units that line up with the list entries. Those units are tokens. A token is a piece of text that later steps treat as one item, usually a word, a number, or a piece of punctuation.
If you filter before tokenising, you have to match stop words against raw strings. That fails in two ways.
The first failure is substring damage. Removing "the" with str.replace also deletes it from inside other words:
text = "the other theme"
print(repr(text.replace("the", ""))) # ' or me'"other" became "or" and "theme" became "me". Adding spaces around the stop word (" the ") fixes some cases. It still misses a stop word at the start or end of the text, next to punctuation, or next to a second stop word ("the the").
The second failure is attached punctuation. A plain whitespace split leaves punctuation stuck to words:
text = "The cat, the dog. Don't stop!"
print(text.split()) # ['The', 'cat,', 'the', 'dog.', "Don't", 'stop!']After case folding, "the" matches the first and third tokens. A word like "stop!" can never match a stop list entry, and neither can "dog.". Tokenising first gives the filter clean units to compare.
What counts as a token
There is no single correct definition. The right one depends on what the later steps need. These are the common choices.
| Strategy | How | Strength | Weakness |
|---|---|---|---|
| Whitespace split | `text.split()` | Fast, no dependencies | Keeps punctuation attached to words |
| Word characters | `re.findall(r"\w+", text)` | Drops punctuation | Splits "don't", "state-of-the-art", and "3.5" |
| Word characters with inner joiners | `re.findall(r"\w+(?:['-]\w+)*", text)` | Keeps contractions and hyphenated words | Still splits "3.5" and "e.g." |
| Library tokeniser (spaCy, NLTK) | Rule sets and exceptions | Handles abbreviations, numbers, URLs | Extra dependency, language-specific rules |
| Subword tokeniser (BPE, WordPiece) | Learned vocabulary | No unknown words | Tokens are not words, so word-level stop lists do not apply |
Here are the first three side by side on one sentence:
import re
text = "Don't use state-of-the-art tools, e.g. 3.5 cm."
print(text.split())
print(re.findall(r"\w+", text))
print(re.findall(r"\w+(?:['-]\w+)*", text))The output is:
["Don't", 'use', 'state-of-the-art', 'tools,', 'e.g.', '3.5', 'cm.']
['Don', 't', 'use', 'state', 'of', 'the', 'art', 'tools', 'e', 'g', '3', '5', 'cm']
["Don't", 'use', 'state-of-the-art', 'tools', 'e', 'g', '3', '5', 'cm']The second line shows why a bare \w+ is risky for stop word work. It produces the fragments t, of, the, and art. Your stop list will then delete of and the from inside "state-of-the-art", and the fragment t will survive as a meaningless token. The third pattern keeps the hyphenated compound as one token, so it is either kept or dropped as a whole.
Normalise before you tokenise
Tokenisers depend on character categories, so the characters must already be in a consistent form. Two problems show up in practice.
Combining marks break `\w`
In Python, \w matches letters, digits, and underscore. Combining marks, such as the accent in the decomposed form of "é", are not letters or digits. A decomposed accent therefore ends the match:
import re
import unicodedata
decomposed = "cafe\u0301 au lait"
print(re.findall(r"\w+", decomposed))
# ['cafe', 'au', 'lait']
composed = unicodedata.normalize("NFC", decomposed)
print(re.findall(r"\w+", composed))
# ['café', 'au', 'lait']The accent is silently dropped, and no error is raised. After NFC, "é" is a single letter and the word stays whole.
Apostrophes come in two forms
Word processors and web pages often use the typographic apostrophe ’ (U+2019) instead of the ASCII '. NFKC does not convert it. If your stop list contains "don't" with an ASCII apostrophe, the token "don’t" will not match. Replace the typographic apostrophe with the ASCII one during normalisation, or include both forms in the tokeniser pattern and the stop list.
Scripts without spaces
Chinese, Japanese, and Thai are written without spaces between words. \w+ returns a whole run of characters as one token, and split() returns the whole sentence. Word-level stop word removal needs a segmenter first, such as jieba for Chinese or MeCab for Japanese.
Filtering with the same normal form
The stop list must pass through the same normalisation as the text. If the text is case folded and the list contains "The", nothing matches. The simplest rule is to build the list by running each entry through your normalise function, rather than trusting that you typed it in the right form.
The pipeline below applies the three steps in order and keeps each token's character offset:
import re
import unicodedata
TOKEN_RE = re.compile(r"\w+(?:['-]\w+)*")
STOP_WORDS = {"the", "a", "an", "is", "of", "and", "to", "in", "don't", "it's"}
def normalise(text):
text = unicodedata.normalize("NFKC", text)
text = text.replace("\u2019", "'")
return text.casefold()
def tokenise(text):
return [(m.group(), m.start()) for m in TOKEN_RE.finditer(text)]
def remove_stop_words(tokens):
return [(tok, pos) for tok, pos in tokens if tok not in STOP_WORDS]
raw = "It\u2019s the \ufb01rst caf\u00e9 in town. Don\u2019t miss it!"
norm = normalise(raw)
print(norm)
# it's the first café in town. don't miss it!
tokens = tokenise(norm)
print(remove_stop_words(tokens))
# [('first', 9), ('café', 15), ('town', 23), ('miss', 35), ('it', 40)]Step by step:
- NFKC turns the ligature
fiinto the two letters "fi". Without it,"first"would never equal"first". - The apostrophe replacement turns
It’sandDon’tinto forms that match the stop list. casefoldlowercases everything, including the initial "I" of "It's".tokeniseyieldsit's,the,first, and so on, withdon'tandit'skept whole.- The filter drops
it's,the,in, anddon't. It keepsit, because "it" is not in this small list.
The offsets in the output are positions in the normalised string. They are not positions in the raw string. In the raw text, "café" starts at index 14, because the ligature is one character. After NFKC it is two characters, and "café" starts at 15.
Choices that affect filtering
Stop word lists are not universal
Libraries ship different lists. NLTK's English list has about 180 words, scikit-learn's has about 320, and they disagree on words like "not", "no", "system", and "fire". Check the list you load. A list that contains "not" turns "not good" into "good", which reverses the sentiment. Stop word removal is a decision about your task, so review the list before using it.
Split contractions need matching entries
Some tokenisers, such as spaCy's and the Penn Treebank tokeniser in NLTK, split "don't" into do and n't. A stop list must then contain n't. A list written for whitespace tokens (don't) will not match. Keep the tokeniser and the list as a pair, and test them together on a handful of contractions.
Filtering and n-grams
If you build bigrams or trigrams, the order matters. Filtering first joins words that were not neighbours: "cost of living" becomes the bigram cost living. Building n-grams first and then dropping those that contain stop words keeps the real adjacency. Choose one on purpose, and apply it the same way at training time and at prediction time.
Numbers, punctuation, and case
Tokenisers differ on whether 3.5, $20, e-mail, or http://example.com is one token. For search or classification, many pipelines map numbers to a placeholder such as <num>. Decide this when you choose the tokeniser, because the filter step cannot recover what the tokeniser split apart.
Common errors
- Filtering with
str.replaceor substring checks instead of token membership. - Running
\w+on text that has not been through NFC or NFKC, which silently cuts words at combining marks. - Building the stop list by hand in a different case or apostrophe style from the normalised text.
- Using a stop list with "not", "no", or "nor" on sentiment data.
- Reporting offsets from normalised text as if they were offsets in the original.
- Using a word-level stop list on the output of a subword tokeniser, where tokens like
##ingnever match any entry.
Practical test
Before trusting a pipeline, run it on a short list of awkward inputs and read the output:
import re
import unicodedata
TOKEN_RE = re.compile(r"\w+(?:['-]\w+)*")
def tokens_of(raw):
text = unicodedata.normalize("NFKC", raw).replace("\u2019", "'").casefold()
return TOKEN_RE.findall(text)
cases = [
"Don\u2019t panic", # typographic apostrophe
"cafe\u0301", # decomposed accent
"\uff34\uff28\uff25 END", # full-width letters
"state-of-the-art", # hyphenated compound
]
for case in cases:
print(tokens_of(case))
# ["don't", 'panic']
# ['café']
# ['the', 'end']
# ['state-of-the-art']Each case is a surface variation that should reduce to one form. If any output surprises you, fix the pipeline before running it on a full corpus.
Exercise
A pipeline casefolds text, splits it with re.findall(r"\w+", text), and removes tokens found in the stop list {"the", "of", "don't", "t"}. Given the input "Don’t read the state-of-the-art paper", it returns ['don', 'read', 'state', 'art', 'paper']. Name two things that are wrong, and give a change for each.
Show answer
First, the typographic apostrophe and the \w+ pattern split "Don’t" into "don" and "t". The "t" is removed by the stop list but "don" survives, so the contraction is not handled as a unit. Replace ’ with ' during normalisation and use a pattern that keeps inner apostrophes, such as \w+(?:['-]\w+)*, so "don't" is one token and matches the stop list. Second, \w+ also split "state-of-the-art" into "state", "of", "the", "art", and the filter then removed "of" and "the" from inside the compound. Allowing inner hyphens in the pattern keeps "state-of-the-art" as one token, so it is kept or dropped as a whole.
Exercise
Your pipeline normalises with NFKC, then tokenises, and a downstream tool highlights tokens in the user's original text using each token's start offset. Highlights drift to the right in some documents. What is the likely cause, and what are two ways to fix it?
Show answer
NFKC can change the length of the text, for example when a ligature such as "fi" becomes "fi", so offsets from the normalised string do not match the original string. One fix is to tokenise the original text, record the offsets there, and normalise each token separately for matching. The other is to keep a mapping from each normalised position back to its original position and translate the offsets before highlighting.