Sub topic 10
Putting the Steps in the Right Order
This chapter assumes you know the individual steps from earlier chapters: casefold(), the four Unicode normalisation forms, accent stripping with unicodedata.combining, and stop word lists. It covers how those steps interact. You will learn which steps must come before which, how to build a pipeline that holds up, and how to check it.
Why order matters
Each cleaning step assumes something about its input. Case folding assumes the text is already one string of code points. Stop word removal assumes tokens and list entries share a form. If an earlier step breaks one of these assumptions, a later step quietly does the wrong thing and raises no error.
The usual failure is a silent miss. A stop word stays in your data, or two strings you expected to match do not. Here is the simplest case, where stop words are removed before case folding:
STOP_WORDS = {"the", "is", "in", "of"}
raw = "The CAF\u00c9 is IN the Field"
# Wrong: filter first, fold later
tokens = raw.split()
kept = [t for t in tokens if t not in STOP_WORDS]
print([t.casefold() for t in kept]) # ['the', 'caf\u00e9', 'in', 'field']
# Right: fold first, filter later
tokens = raw.casefold().split()
print([t for t in tokens if t not in STOP_WORDS]) # ['caf\u00e9', 'field']The wrong order leaves "The" and "IN" in the output because the list only contains lowercase forms.
The dependency rules
The order follows from a few rules. Each one comes from a failure you can reproduce.
- Decode bytes to
strfirst. Every later step works on code points, not bytes. - Normalise Unicode before anything that compares characters. Case folding, accent stripping, and list lookups all compare code points, so the text must reach one canonical form first.
- Re-normalise after case folding. Folding can change the length of a string and can emit combining marks.
- Collapse whitespace after compatibility normalisation, because NFKC turns exotic spaces into plain ones.
- Tokenise before filtering words. Stop word removal works on tokens, not on raw strings.
- Run stop word removal last, using a list that went through the same steps as the text.
Normalise before comparing
The two spellings of "café" from the Unicode chapter show why rule 2 comes first. Folding alone does not make them equal:
import unicodedata
a = "caf\u00e9"
b = "CAFE\u0301"
print(a == b.casefold()) # False: the accent is still a separate code point
folded = unicodedata.normalize("NFKC", b).casefold()
print(a == folded) # TrueRe-normalise after folding
Case folding is not guaranteed to return text in a normal form. The capital "İ" (U+0130, used in Turkish) folds to two code points: "i" plus a combining dot above.
s = "\u0130stanbul"
folded = s.casefold()
print(len(s), len(folded)) # 8 9
print([hex(ord(c)) for c in folded[:2]]) # ['0x69', '0x307']A string that grew by one code point may differ from the same word typed another way. The Unicode standard's recipe for caseless matching therefore normalises, folds, and normalises again. The pipeline below does this too.
Collapse whitespace after NFKC
Python's \s already matches a no-break space, so re.sub(r"\s+", ...) is safe at any point. Patterns that name the space character directly are not:
import re
import unicodedata
raw = "a\u00a0\u00a0b"
print(repr(re.sub(r" +", " ", raw))) # 'a\xa0\xa0b'
nfkc = unicodedata.normalize("NFKC", raw)
print(repr(re.sub(r" +", " ", nfkc))) # 'a b'Running NFKC first means the whitespace step sees only plain spaces. That makes it independent of how your regular expression is written.
Tokenise before removing punctuation
Deleting punctuation before tokenising merges or splits words in ways the stop word list cannot recognise:
import re
text = "I don't like e-mail"
print(re.sub(r"[^\w\s]", "", text)) # I dont like email
print(re.findall(r"\w+", text)) # ['I', 'don', 't', 'like', 'e', 'mail']If your list contains "don't", neither result matches it. Choose one tokenisation rule, keep internal apostrophes in it, and make the list follow that rule.
A pipeline that follows the rules
The diagram shows the order used by the code that follows. Accent stripping is optional and sits after folding.
import re
import unicodedata
def strip_accents(text):
decomposed = unicodedata.normalize("NFD", text)
kept = "".join(ch for ch in decomposed if not unicodedata.combining(ch))
return unicodedata.normalize("NFC", kept)
def normalise(text, accents=False):
text = unicodedata.normalize("NFKC", text)
text = text.casefold()
text = unicodedata.normalize("NFKC", text)
if accents:
text = strip_accents(text)
text = text.replace("\u2019", "'")
return re.sub(r"\s+", " ", text).strip()
def tokenise(text):
return re.findall(r"\w+(?:'\w+)*", text)
def clean(text, stop_words, accents=False):
stops = {normalise(w, accents) for w in stop_words}
tokens = tokenise(normalise(text, accents))
return [t for t in tokens if t not in stops]
STOP_WORDS = ["The", "is", "isn't", "in", "of"]
raw = "The CAF\u00c9 isn\u2019t in the \ufb01eld\u00a0of \u00c9toiles"
print(clean(raw, STOP_WORDS)) # ['caf\u00e9', 'field', '\u00e9toiles']
print(clean(raw, STOP_WORDS, accents=True)) # ['cafe', 'field', 'etoiles']Several details are deliberate:
- The stop word list passes through
normalisewith the sameaccentssetting as the text. The entry "The" becomes "the" and matches. Without this, "The" in the list would never match anything. - The curly apostrophe (U+2019) becomes a straight one. NFKC does not do this, so it is a separate explicit step. Without it, "isn’t" and "isn't" are different tokens.
- NFKC turns the ligature in "field" and the no-break space into "fi" and a plain space before the tokeniser runs.
Choosing the normalisation form
NFKC is the default above because it merges the most variants. It is lossy, though.
| Form | Merges | Loses | Use when |
|---|---|---|---|
| NFC | Precomposed and decomposed accents | Nothing meaningful | You must keep the text's appearance, such as for named entities |
| NFKC | The above, plus ligatures, full-width letters, no-break spaces | Superscripts, subscripts, fractions, and the trademark sign become plain characters | Search and classification where "H₂O" and "H2O" may be treated alike |
| NFD | Splits marks from base letters | Nothing | Immediately before stripping accents |
| NFKD | NFD plus compatibility mapping | Same as NFKC | Rarely needed on its own |
NFKC turns "H₂O" into "H2O" and "²" into "2". If the difference matters for your data, use NFC and handle ligatures and spaces with explicit replacements.
Testing the pipeline
A cleaning function should be idempotent: running it twice gives the same result as running it once. Order mistakes often break this property, because a later step creates something an earlier step would have changed. A short check catches many of them.
import re
import unicodedata
def normalise(text):
text = unicodedata.normalize("NFKC", text)
text = text.casefold()
text = unicodedata.normalize("NFKC", text)
return re.sub(r"\s+", " ", text).strip()
samples = [
"Stra\u00dfe",
"\u0130stanbul",
"CAFE\u0301",
"\ufb01eld",
"a\u00a0\u00a0b",
" padded text ",
]
for s in samples:
once = normalise(s)
assert normalise(once) == once, s
print(repr(once))A second useful test is equivalence: strings that people consider the same should clean to the same output. For example, normalise("Stra\u00dfe") == normalise("STRASSE") should hold. Collect real pairs from your own data, because the edge cases that matter depend on your languages.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Filtering stop words before folding | "The" and "IN" survive | Fold first |
| Stripping accents from text but not from the list | Accented stop words survive | Run the list through `normalise` |
| Removing punctuation before tokenising | "don't" becomes "dont", splits, or never matches | Tokenise with a rule that keeps apostrophes, then filter |
| Folding last, with no re-normalisation | Strings that look equal have different lengths | Normalise again after `casefold()` |
| Using NFKC where symbols matter | Subscripts and fractions change meaning | Use NFC and explicit replacements |
| Stripping accents too early | Words that differ only by accent merge, such as "résumé" and "resume" | Strip only when the task tolerates it |
When the order should change
The order above suits search and bag-of-words classification. Other tasks call for fewer steps, not a different order. Skipping a step is covered in the last chapter, so only the interaction with order matters here. If you skip case folding for named entity recognition, keep the Unicode normalisation step, because the same name in two encodings still needs to match. If you skip stop word removal, the whole stop word branch of the pipeline disappears, including the requirement to process the list.
Exercise
The text "Don’t STOP" (with a curly apostrophe) is cleaned with re.findall(r"\w+", text.casefold()) and then filtered against a stop list containing "don't". Name two problems and say how the pipeline in this chapter avoids each one.
Show answer
First, \w+ splits "don’t" into "don" and "t", so the list entry "don't" can never match; the pipeline's tokeniser \w+(?:'\w+)* keeps the apostrophe inside the token. Second, even with a better tokeniser the curly apostrophe (U+2019) differs from the straight one in the list; the pipeline replaces U+2019 with "'" in normalise, and it runs the list through the same function, so both sides use the same character.
Exercise
A colleague moves strip_accents to run before normalize("NFKC", ...) and casefold(), and removes the second NFKC call. Which input shows a problem, and what is it?
Show answer
Any input where folding creates a combining mark or a non-normalised sequence after the accent step has finished. The text "İstanbul" folds to "i" plus U+0307, and because accent stripping already ran, the dot above stays in the output and the result differs from "istanbul". Folding before stripping, with a normalisation pass between them, removes the mark.
Exercise
You run normalise on a French document and then remove stop words with a list that includes "à" and "être". You strip accents from the text. What is the bug, and what is the simplest fix?
Show answer
The text contains "a" and "etre", but the list still contains "à" and "être", so those entries never match and the words stay in the output. The simplest fix is to build the stop set with {normalise(w, accents=True) for w in STOP_WORDS}, so the list and the text use the same options.