Sub topic 4
Normalising text before and after tokenising
This chapter assumes you can write basic Python (strings, lists, functions, regular expressions) and that you know what a token and a type are from the earlier chapters. You should also be comfortable with the idea of an NLP task such as search or classification, because the right normalisation depends on the task.
What normalisation does
Normalisation maps different surface forms of text onto one shared form. "Apple", "apple" and "APPLE" become one string. A letter written as one Unicode character and the same letter written as two characters become one sequence. After normalisation, your program treats equivalent strings as equal.
The benefit is a smaller vocabulary. Every variant you merge removes a type from your vocabulary, and the counts for the surviving type go up. Models and indexes see fewer, better-estimated types. The cost is lost information. Once you lower-case "US" (the country) it becomes the same as "us" (the pronoun), and you cannot recover the distinction.
So normalisation is a set of trade-offs, not a fixed recipe. This chapter covers two core steps, case folding and Unicode normalisation. It then covers a few other common steps and the question of where in the pipeline each step belongs.
Case folding
Lower-casing is the simplest form of case folding. It is useful for search and for bag-of-words classifiers, where "The" at the start of a sentence should count as the same type as "the" in the middle.
Python gives you two methods. str.lower() converts to lower case. str.casefold() is more aggressive and is designed for caseless comparison. It handles characters whose lower-case form does not match across variants. The standard example is German "ß", which casefold() turns into "ss".
print("Straße".lower())
print("Straße".casefold())
print("STRASSE".casefold() == "Straße".casefold())The output is straße, then strasse, then True. With lower() alone, "STRASSE" and "Straße" would stay different.
Side effects of lower-casing
- Lost named entities. "Apple" (company) and "apple" (fruit) merge. "Bush", "Polish" and "March" have the same problem. Named-entity recognisers and part-of-speech taggers often use capitalisation as a feature, so lower-casing hurts them.
- Lost emphasis and sentiment cues. "This is GREAT" and "this is great" carry different intensity. Some sentiment classifiers benefit from keeping all-caps tokens.
- Language-specific rules. Turkish has dotted and dotless I. The upper-case "I" should lower-case to "ı" (dotless), but Python's
lower()is not locale-aware and returns "i". If you process Turkish, use a library that applies Turkish rules, or handle those letters explicitly. - Final sigma in Greek.
lower()chooses a final form "ς" at the end of a word, whilecasefold()always uses "σ". Folding gives you consistency, and the visual form is less correct. That is acceptable for matching and wrong for display.
A common compromise is truecasing: lower-case only words that are capitalised just because they start a sentence, and keep other capitals. It needs a model or a heuristic and is more work than casefold(), so use it only when capitalisation carries signal for your task.
Unicode normalisation
Unicode lets you write the same visible text in several different ways. The letter "é" can be one code point, U+00E9 (precomposed). It can also be "e" followed by U+0301, a combining acute accent (decomposed). Both display identically, but Python compares code points, so the strings are not equal.
import unicodedata
composed = "caf\u00e9"
decomposed = "cafe\u0301"
print(composed == decomposed)
print(unicodedata.normalize("NFC", composed) == unicodedata.normalize("NFC", decomposed))
print("Straße".casefold())The output is False, True, then strasse. Text from different sources often differs in this way. macOS file names, PDF extractions and keyboard input methods can each produce a different form. Without normalisation, the same word appears as two types, and a search for "café" misses documents that contain the decomposed form.
The four normal forms
Unicode defines four normal forms. The letters stand for Normalisation Form C, D, KC and KD.
| Form | Composition | Compatibility mapping | Typical use |
|---|---|---|---|
| NFC | Composes sequences into single code points | No | Default for storing and comparing text |
| NFD | Decomposes into base character plus marks | No | Step before removing accents |
| NFKC | Composes | Yes | Aggressive cleanup for search and matching |
| NFKD | Decomposes | Yes | Aggressive cleanup plus accent removal |
The "K" forms apply compatibility mappings. These replace characters that are visually or semantically similar with a plain equivalent. Examples are the ligature "fi" (U+FB01) becoming "fi", the circled digit "①" becoming "1", and full-width "ABC" becoming "ABC". This is valuable for matching, but it is lossy. A superscript "²" becomes "2", so "m²" becomes "m2". Use NFC when you must preserve the text, and use NFKC when you only need a canonical key for comparison.
Tokenisation depends on normalisation
Unicode form affects tokenisers directly. The regular expression from the earlier chapter treats a combining mark as punctuation, because a mark is not a letter or digit as far as \w is concerned.
import re
import unicodedata
pattern = r"\w+(?:'\w+)?|[^\w\s]"
decomposed = "cafe\u0301"
print(len(re.findall(pattern, decomposed)))
normalised = unicodedata.normalize("NFC", decomposed)
print(len(re.findall(pattern, normalised)))The first count is 2: the tokeniser emits "cafe" and then the lone accent as a separate punctuation token. The second count is 1. The decomposed form of a word gets split in the middle. This is one reason to apply Unicode normalisation before tokenising.
Other common steps
- Accent stripping. Turning "café" into "cafe" helps when users type without accents. It also merges words that differ only by accent, such as Spanish "sí" (yes) and "si" (if), or French "côte" and "coté". Strip accents only if your users or data are inconsistent about them.
- Whitespace cleanup. Collapse runs of spaces, tabs, newlines and non-breaking spaces (U+00A0) into a single space. NFKC converts U+00A0 to an ordinary space, which helps.
- Quotes and dashes. Curly quotes (“ ”) and apostrophes (’) differ from the ASCII characters ( " and ' ). A tokeniser that expects
'in "don't" will split "don’t" apart. Map curly forms to ASCII first. NFKC does not do this, so you need an explicit replacement table. - Number and URL handling. Replacing digits with a placeholder such as
<NUM>shrinks the vocabulary. It also destroys information, so do it only when the exact value does not matter. - Punctuation removal. This is common in bag-of-words pipelines. It also deletes the apostrophe in "don't", turns "e-mail" into "e mail" or "email" depending on the rule, and removes emoticons and sentiment signals like "!!!".
Before or after tokenising
Some steps run on the whole string before tokenising. Others run on each token afterwards. The order matters.
Run these before tokenising:
- Unicode normalisation, because the tokeniser's character classes depend on the form.
- Quote and whitespace cleanup, because the tokeniser's contraction rules expect plain characters.
Run these after tokenising, or make them depend on the tokens:
- Case folding when the tokeniser uses capitalisation. Many sentence splitters and abbreviation rules (for example "Dr. Smith") need case. If you lower-case first, you lose that signal.
- Stop-word removal, number replacement and stemming or lemmatisation, which work on individual tokens.
- Accent stripping, if you want to keep the accented form for another feature.
Order also matters among the string-level steps. Case folding can produce characters that need renormalising, so the safest sequence is normalise, fold, normalise again. Accent stripping must come after decomposition, because it works by removing the combining marks that NFD splits off.
In the diagram, case folding sits after the tokeniser. For a simple search index you can fold earlier, and the result is the same. The diagram shows the safer general order.
A reusable function
This function combines the string-level steps. It applies NFKC, case folds, normalises again, and optionally strips accents.
import re
import unicodedata
def normalise(text, strip_accents=False):
text = unicodedata.normalize("NFKC", text)
text = unicodedata.normalize("NFKC", text.casefold())
if strip_accents:
decomposed = unicodedata.normalize("NFD", text)
kept = [c for c in decomposed if unicodedata.category(c) != "Mn"]
text = unicodedata.normalize("NFC", "".join(kept))
return re.sub(r"\s+", " ", text).strip()
raw = " The \ufb01nal CAF\u00c9 Stra\u00dfe \u2460 "
print(normalise(raw))
print(normalise(raw, strip_accents=True))The output is:
the final café strasse 1
the final cafe strasse 1The ligature "fi" became "fi", "ß" became "ss", the circled digit became "1", and the extra spaces collapsed. In the second call, unicodedata.category(c) != "Mn" removed the combining marks (category Mn, "mark, nonspacing") after NFD had split them from their base letters.
Common errors
- Comparing without normalising. Two strings that look identical fail an equality test or a dictionary lookup. Normalise both sides, and normalise the stored data and the query in the same way.
- Using
lower()wherecasefold()is needed. For caseless matching in multiple languages, prefercasefold(). - Applying NFKC to text you must preserve. Compatibility mappings change meaning in chemistry ("H₂O" becomes "H2O"), mathematics and units. Keep the original text and store the normalised version as a separate key.
- Normalising training data but not production input. A model trained on lower-cased text sees unknown capitalised words at inference time. Use one function in both places.
- Over-normalising. Each step removes information. Add a step only when you can name the variation it removes and the task it helps.
Evaluating a normalisation step
Treat each step as a hypothesis and test it. Measure the vocabulary size before and after, using the type count from the first chapter. A step that barely shrinks the vocabulary is probably not worth its side effects. Then compare your task metric (retrieval recall, classification accuracy) with and without the step on held-out data. The metric decides, and vocabulary size alone does not.
Exercise
A search engine indexes product reviews in French and Spanish. Users often type queries without accents, but the reviews are written with accents. Which steps from this chapter would you apply to both the index and the query, and what is the main risk of the accent step?
Show answer
Apply NFC (or NFKC) Unicode normalisation, case folding with casefold(), and whitespace cleanup to both documents and queries, so the same function produces the index keys and the search terms. Add accent stripping (NFD, drop Mn marks, recompose) to both sides so that "cafe" matches "café". The main risk is merging words that differ only by an accent, such as Spanish "sí" and "si", which can return irrelevant results. Keeping the original text for display and ranking, and using the stripped form only as a matching key, limits the damage.
Exercise
The string "cafe\u0301" is passed to the tokeniser pattern r"\w+(?:'\w+)?|[^\w\s]". How many tokens does it produce, and what single change makes it produce one token?
Show answer
It produces two tokens: "cafe" and the lone combining accent U+0301, which \w does not match, so the [^\w\s] branch emits it as a punctuation token. Applying unicodedata.normalize("NFC", text) before tokenising composes the sequence into "café", which produces one token.