Text Normalisation: Unicode, Case and Noise
Two support tickets say "café" and look identical on screen, yet a dictionary lookup finds one and misses the other. A search for "strasse" misses "Straße". A spam filter learns a separate weight for every order number it has ever seen. All three are normalisation problems: the same thing written in different ways, or different things that should count as one. Normalisation decides which strings are equal before anything else in the pipeline sees them, so its mistakes propagate into the vocabulary, the counts, the weights and the search index.
Preparing Text Data covered the basic toolkit: fixing mojibake, NFKC, collapsing whitespace and a table of what each step costs. This lesson goes one level down: what the four Unicode normal forms actually do, why lower() is not case folding, how accent stripping works and where it fails, how to replace URLs, numbers and emoji with placeholders, and why almost none of this should be applied in front of a pretrained transformer.
One character, several byte sequences
Unicode assigns a code point to each abstract character, but many characters can be written in more than one way. "é" exists as a single precomposed code point (U+00E9) and as "e" followed by a combining acute accent (U+0301). Both render the same; Python compares code points, so they are different strings. Keyboards on macOS, copy-paste from PDFs and some databases produce the decomposed form, while most web text is precomposed, so a real corpus contains both.
Unicode defines four normal forms that make such strings comparable:
| Form | What it does | Typical use |
|---|---|---|
| NFC | canonical decomposition, then recomposition: one code point where one exists | storage, display, equality checks |
| NFD | canonical decomposition: base letter + combining marks | accent stripping, character-level processing |
| NFKC | compatibility decomposition, then recomposition: also maps "look-alike" variants to a plain form | search, bag of words, deduplication |
| NFKD | compatibility decomposition without recomposition | rarely used directly |
Canonical equivalence means the two sequences are the same character (é and e + accent). Compatibility equivalence is weaker: the ligature "fi" and "fi", a full-width "A" and "A", a superscript two and a plain "2" mean roughly the same thing but are not the same character. NFKC removes those differences and with them some information.
import unicodedata
a = "caf\u00e9" # é as one code point (precomposed)
b = "cafe\u0301" # e + COMBINING ACUTE ACCENT
print(a, b, a == b, len(a), len(b))
for form in ("NFC", "NFD", "NFKC", "NFKD"):
na, nb = unicodedata.normalize(form, a), unicodedata.normalize(form, b)
print(f"{form:4} equal={na == nb} lengths={len(na)},{len(nb)}")
print([unicodedata.name(c) for c in b])
compat = ["\ufb01le", "\uff21\uff22\uff23 123", "x\u00b2", "\u2460", "\u2167", "\u00bd", "km\u00b2"]
for s in compat:
print(f"{s!r:12} NFC {unicodedata.normalize('NFC', s)!r:12} NFKC {unicodedata.normalize('NFKC', s)!r}")café café False 4 5
NFC equal=True lengths=4,4
NFD equal=True lengths=5,5
NFKC equal=True lengths=4,4
NFKD equal=True lengths=5,5
['LATIN SMALL LETTER C', 'LATIN SMALL LETTER A', 'LATIN SMALL LETTER F', 'LATIN SMALL LETTER E', 'COMBINING ACUTE ACCENT']
'file' NFC 'file' NFKC 'file'
'ABC 123' NFC 'ABC 123' NFKC 'ABC 123'
'x²' NFC 'x²' NFKC 'x2'
'①' NFC '①' NFKC '1'
'Ⅷ' NFC 'Ⅷ' NFKC 'VIII'
'½' NFC '½' NFKC '1⁄2'
'km²' NFC 'km²' NFKC 'km2'
The two cafés differ in length (4 against 5 code points) and compare unequal, and every normal form makes them equal. NFC leaves the compatibility characters alone; NFKC flattens them, which is what search usually wants ("file" should match "file") and what a maths or chemistry corpus does not: x² becomes x2 and km² becomes km2, and the fraction one half becomes "1", a fraction slash and "2". A sensible default is NFC for storage and NFKC for matching, keeping the original text next to the normalised one.
Note: NFKC is not a security filter. Many visually confusable characters (Cyrillic "а" and Latin "a", for instance) are different letters and stay different under every normal form. Detecting look-alike spoofing needs Unicode's separate confusables data.
Case folding is not lowercasing
str.lower() maps each character to its lowercase form. Case folding (str.casefold()) is designed for caseless comparison, and it differs in exactly the places where lowercasing fails to make equal words equal.
import unicodedata
words = ["Straße", "STRASSE", "İstanbul", "ΣΟΦΟΣ", "DŽemal"]
for w in words:
print(f"{w:9} lower={w.lower()!r:12} casefold={w.casefold()!r}")
print("Straße".lower() == "STRASSE".lower(), "Straße".casefold() == "STRASSE".casefold())
print(len("İ".lower()), [unicodedata.name(c) for c in "İ".lower()])
def strip_accents(s):
decomposed = unicodedata.normalize("NFD", s)
kept = "".join(c for c in decomposed if unicodedata.category(c) != "Mn")
return unicodedata.normalize("NFC", kept)
for s in ["café crème", "Nguyễn Thị Minh Khai", "São Paulo", "Ångström", "łódź", "Øresund"]:
print(f"{s:22} -> {strip_accents(s)}")Straße lower='straße' casefold='strasse'
STRASSE lower='strasse' casefold='strasse'
İstanbul lower='i̇stanbul' casefold='i̇stanbul'
ΣΟΦΟΣ lower='σοφος' casefold='σοφοσ'
DŽemal lower='džemal' casefold='džemal'
False True
2 ['LATIN SMALL LETTER I', 'COMBINING DOT ABOVE']
café crème -> cafe creme
Nguyễn Thị Minh Khai -> Nguyen Thi Minh Khai
São Paulo -> Sao Paulo
Ångström -> Angstrom
łódź -> łodz
Øresund -> Øresund
German "ß" has no single uppercase letter in traditional spelling; its uppercase is "SS". Lowercasing "STRASSE" gives "strasse", lowercasing "Straße" keeps the "ß", so the comparison is False; case folding maps "ß" to "ss" and the two match. Greek shows the opposite subtlety: Python's lower() knows that a capital sigma at the end of a word becomes the final form, while casefold() maps every sigma to the same letter, which is right for matching and wrong for display. Turkish is the classic trap: the dotted capital "İ" lowercases to two code points, "i" plus a combining dot, so the lowercased string is one character longer than the original and a naive character-by-character alignment breaks. Correct Turkish casing ("I" to dotless "ı") needs a locale, which neither method takes.
The rule of thumb: use casefold() when comparing or indexing, lower() never for matching, and keep the original string for display.
Stripping accents
Accent stripping decomposes with NFD, drops every character of Unicode category Mn (non-spacing mark, the combining accents) and recomposes. It turns "Nguyễn Thị Minh Khai" into "Nguyen Thi Minh Khai", which helps users who type without accents, a very common habit in Vietnamese and French search boxes. It also has limits that the output shows: "ł" and "Ø" are separate letters, not letters with a combining mark, so they survive. Libraries such as unidecode add hand-written transliteration tables for those.
Stripping accents is lossy in a way that matters for some languages. In Vietnamese the tone marks distinguish words: "ma", "má", "mà", "mả", "mã" and "mạ" are six different words, and all become "ma". In Spanish "año" (year) and "ano" differ only by the tilde. Strip accents for matching (a second, accent-free search field), not for the text a model learns from.
How much does each step merge?
Each step trades distinctions for counts: a merged word collects the statistics of all its variants, but words that really were different are now confused. The example applies case folding, accent stripping and both to 18 words and counts how many types (distinct strings) survive.
import unicodedata
from collections import defaultdict
def strip_accents(s):
d = unicodedata.normalize("NFD", s)
return unicodedata.normalize("NFC", "".join(c for c in d if unicodedata.category(c) != "Mn"))
steps = {
"casefold": str.casefold,
"strip accents": strip_accents,
"both": lambda w: strip_accents(w.casefold()),
}
words = ["US", "us", "Apple", "apple", "résumé", "resume", "Polish", "polish",
"May", "may", "pâté", "pate", "WHO", "who", "Nice", "nice", "Turkey", "turkey"]
for name, f in steps.items():
groups = defaultdict(list)
for w in words:
groups[f(w)].append(w)
merged = [g for g in groups.values() if len(g) > 1]
print(f"{name:13} {len(words)} -> {len(groups)} types; merged: {merged[:3]}")casefold 18 -> 11 types; merged: [['US', 'us'], ['Apple', 'apple'], ['Polish', 'polish']]
strip accents 18 -> 16 types; merged: [['résumé', 'resume'], ['pâté', 'pate']]
both 18 -> 9 types; merged: [['US', 'us'], ['Apple', 'apple'], ['résumé', 'resume']]
Case folding reduces 18 words to 11 types and merges pairs that mean different things (the country and the pronoun, the company and the fruit, the nationality and the verb, the health organisation and the question word). Accent stripping alone goes to 16 and merges "résumé" with "resume". With both, 9 types are left. On a large corpus the same effect shows up as a smaller vocabulary and denser counts: for a bag-of-words model trained on a few thousand documents that is usually a win, because "Refund" at the start of a sentence and "refund" in the middle are the same feature. With millions of documents and a model that can use context, it is mostly a loss.
Noise: placeholders instead of deletion
User text is full of tokens that are unique but uninformative as strings: URLs, e-mail addresses, order numbers, phone numbers, emoji, repeated letters. Each new order number adds a vocabulary entry that will never be seen again. Deleting them throws away a useful signal ("this ticket contains a link", "this message has a number"); replacing them with a placeholder token keeps the signal and drops the identity. Placeholders also remove personal data (e-mail addresses, phone numbers) from the features, which matters for logging and for models that might memorise them.
Order matters. URLs contain digits and dots, so they must be replaced before numbers; e-mail addresses before anything that splits on "@"; zero-width characters (invisible spaces that break words apart and are a common trick to dodge filters) before everything else.
import re
import unicodedata
URL = re.compile(r"https?://\S+|www\.\S+")
EMAIL = re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b")
NUM = re.compile(r"\b\d+(?:[.,]\d+)*\b")
EMOJI = re.compile("[\U0001F300-\U0001FAFF\u2600-\u27BF]")
ZERO_WIDTH = re.compile("[\u200b\u200c\u200d\u2060\ufeff]")
REPEAT = re.compile(r"(.)\1{2,}")
def normalise(s, lower=True):
s = unicodedata.normalize("NFKC", s)
s = ZERO_WIDTH.sub("", s)
s = URL.sub(" <url> ", s)
s = EMAIL.sub(" <email> ", s)
s = EMOJI.sub(" <emoji> ", s)
s = NUM.sub(" <num> ", s)
s = REPEAT.sub(r"\1\1", s) # sooooo -> soo, !!!!! -> !!
if lower:
s = s.casefold()
return re.sub(r"\s+", " ", s).strip()
msgs = [
"Order #48213 arrived BROKEN 😡 see https://tad.example/p/48213?ref=mail",
"sooooo happy!!!!! refund of 12,50 EUR came in 2 days 🎉",
"Contact me at Anna.B+shop@mail.example or call 0912 345 678",
"pass\u200bword reset link www.tad.example/reset doesn't work",
]
for m in msgs:
print(normalise(m))
vocab_raw = {w for m in msgs for w in m.split()}
vocab_norm = {w for m in msgs for w in normalise(m).split()}
print("distinct whitespace tokens:", len(vocab_raw), "->", len(vocab_norm))order # <num> arrived broken <emoji> see <url>
soo happy!! refund of <num> eur came in <num> days <emoji>
contact me at <email> or call <num> <num> <num>
password reset link <url> doesn't work
distinct whitespace tokens: 33 -> 27
The hidden zero-width space inside "pass word" is gone, so the word is "password" again; the URL with its order number becomes <url>, "12,50" a single <num>, the e-mail <email>. Repeats are capped at two rather than one, so "!!!!!" keeps its emphasis as "!!" and "soo" stays distinguishable from "so". The emoji pattern is deliberately coarse: it covers the common emoji blocks, not every emoji (flags, skin-tone modifiers and joined sequences span several code points). If the emoji carry sentiment, map them to names (<emoji_angry>) instead of one shared token. Four messages are too few to show it, but on real ticket logs placeholder replacement often removes a large share of the vocabulary's one-off entries.
What not to normalise for transformers
Everything above is for models that treat each string as an opaque feature: bag of words, TF-IDF, BM25, n-gram models. A pretrained transformer is different. Its tokenizer has a fixed normalisation built in, chosen when the model was pretrained, and the model learned from text normalised exactly that way. Applying your own rules on top changes the input distribution the model saw.
from transformers import AutoTokenizer
from transformers.utils import logging
logging.set_verbosity_error()
bert = AutoTokenizer.from_pretrained("google/bert_uncased_L-2_H-128_A-2")
gpt2 = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")
for text in ["Café in Paris", "cafe in paris"]:
print("BERT uncased:", bert.tokenize(text))
for text in ["Apple shares rose", "apple shares rose", "APPLE SHARES ROSE"]:
print("GPT-2:", gpt2.tokenize(text), gpt2(text)["input_ids"])BERT uncased: ['cafe', 'in', 'paris']
BERT uncased: ['cafe', 'in', 'paris']
GPT-2: ['Apple', 'Ġshares', 'Ġrose'] [16108, 7303, 8278]
GPT-2: ['apple', 'Ġshares', 'Ġrose'] [18040, 7303, 8278]
GPT-2: ['AP', 'PLE', 'ĠSHARES', 'ĠR', 'OSE'] [2969, 16437, 44806, 371, 14058]
The uncased BERT tokenizer lowercases and strips accents itself, so "Café in Paris" and "cafe in paris" give the same tokens: doing it yourself is redundant. The GPT-2 tokenizer (the same byte-level BPE as tiktoken's gpt2 encoding) does no normalisation at all. "Apple" and "apple" are different tokens with different ids, and the model has learned that the capitalised one is often the company. Lowercasing the input throws that away. All capitals is worse: it breaks the words into rare pieces ("AP", "PLE") that the model saw much less often. So for a cased model, pass the text as written; for an uncased one, let its tokenizer do the lowercasing.
What is still worth doing in front of a transformer: decode bytes correctly, fix mojibake, apply NFC (or NFKC if the tokenizer itself does, as many SentencePiece models do), remove zero-width and control characters, collapse runs of whitespace, and replace personal data if it must not reach the model or the logs. Truncation, padding and the model's tokenizer are covered in Preparing Text Data and later in Tokenizers in Practice.
Pitfalls
- Normalising the training set and not the queries (or the other way round). The normalisation function is part of the model: version it, and run the same function at training and at serving time.
- Different normal forms in two systems. A database in NFD and an index in NFC never match. Normalise at the boundary where text enters your system.
- Lowercasing before named-entity recognition or for a cased model. Case is one of the strongest signals for names and acronyms.
- Stripping accents from training text in tone languages. Vietnamese without tone marks is ambiguous; strip only in a secondary search field.
- Deleting instead of replacing. Numbers, links and emoji carry signal; placeholders keep it.
- Assuming
len()is stable. Lowercasing "İ" adds a code point, NFKC can shorten or lengthen strings. Character offsets computed before normalisation (for highlighting or NER spans) no longer point to the right place afterwards; keep a mapping or work on the original.
Practice
- Two product names, "Tad Bike" (full-width letters) and "Tad Bike", should match in search. Which normal form makes them equal, and would NFC alone do it?
- You lowercase all text with
lower()and later find that "STRASSE" and "Straße" are two features. What one change fixes it? - Why must the URL pattern run before the number pattern in the placeholder function?
- A colleague strips accents from a Vietnamese sentiment dataset to "reduce sparsity". What could go wrong?
- You fine-tune a cased GPT-style model on support tickets and lowercase all tickets first. Name two effects on the token sequences.
Answers
- NFKC: full-width forms are compatibility variants of the ASCII letters. NFC only handles canonical equivalence, so it leaves the full-width letters as they are and the strings stay different.
- Use
casefold()instead oflower(): it maps "ß" to "ss", so both become "strasse". - URLs contain digits (here an order number). If numbers were replaced first, the
<num>placeholder and its spaces would cut the URL in two, the URL pattern would only catch the part before the number, and fragments such as?ref=mailwould be left behind as tokens. - Tone marks distinguish words in Vietnamese, so different words merge into one string (six words become "ma"), including words with different sentiment. The model loses information it cannot get back.
- Capitalised words that the model knows as single tokens ("Apple") become different tokens ("apple") with different learned meanings, and the model no longer sees the case cues it learned in pretraining; the input distribution moves away from what the model saw, so it needs more fine-tuning data to adapt. Token counts change too, since the lowercase split of a word can have a different number of pieces.
Test yourself
Which normal form maps the ligature fi to the two letters fi?
- NFC
- NFD
- NFKC
- None: it is already the same character
Why do "Straße".lower() and "STRASSE".lower() differ?
lower()keepsß, while the uppercase spelling hasSS;casefold()mapsßtosslower()strips accents- Python lowercases only ASCII letters
- The strings are in different normal forms
In the merge experiment, case folding reduced 18 words to how many types?
- 16
- 11
- 9
- 18
You use a cased pretrained transformer. Which preprocessing step should you usually skip?
- Fixing mojibake
- Removing zero-width characters
- Lowercasing
- Unicode NFC