Text normalization: choose what a key may forget
文本规范化
Trace Unicode forms, case folding, collisions and annotation offsets with a complete version-reported Python pipeline.
text-normalizationTwo identical-looking names, two different keys
Suppose a small document collection contains Café twice. One copy ends with the single code point U+00E9; the other ends with U+0065 followed by U+0301. Python sees different strings. A dictionary can therefore keep two entries even when the names look identical on screen. Our first experiment makes both strings share a key.
Now try the same operation on ① and 1, or on the mathematical symbol ℝ and the letter R. Whether these should share a key depends on what the collection is for. A broad search field may benefit from merging some spellings; a transcription of mathematical notation may need the distinction. Text normalization is a declared mapping, with a cost: different inputs may become indistinguishable.
Keep three objects separate: the original text, the derived key used for a particular task, and the policy that produced that key. The program below retains all three. It also records intermediate strings so a reader can locate the step that changed a length or merged two values.
This is a text-processing topic, not the feature scaling used in machine learning. It ends before tokenization: a normalized string still needs a separate decision about word or subword boundaries.
Choose the equivalence before choosing the function
Four forms, two separate choices
Unicode distinguishes canonical equivalence from the broader compatibility equivalence. NFD uses canonical decomposition; NFC follows that with canonical composition. NFKD includes compatibility decomposition; NFKC follows that with canonical composition. Ordering combining marks is part of normalization. These forms do not mean “make everything ASCII.” UAX 15, §§1.1–1.3
Our executable cases expose the practical difference. Here \u0301 denotes the combining acute accent, not six literal characters in the input:
| Input | NFC output | NFD output | NFKC output | NFKD output |
|---|---|---|---|---|
Café | Café | Cafe\u0301 | Café | Cafe\u0301 |
Cafe\u0301 | Café | Cafe\u0301 | Café | Cafe\u0301 |
① | ① | ① | 1 | 1 |
AI | AI | AI | AI | AI |
ℝ | ℝ | ℝ | R | R |
Let N be one fixed normalization form at one fixed Unicode version, applied to accepted strings. The following are useful properties to test, not a reason to treat all normalization policies as interchangeable:
This is idempotence: applying the same normalization again leaves its result unchanged. It says nothing about whether losing a distinction was appropriate. The constant mapping that sends every input to an empty string is also idempotent.
For any deterministic key function K, define its induced equivalence by equality of keys:
This relation is reflexive, symmetric and transitive because equality is. Its classes identify precisely which inputs a downstream lookup can no longer distinguish. This observation applies to our case-and-space policy as well as to a Unicode form, although the classes need not be the same.
Extra steps are additional decisions
The program optionally applies Python’s casefold() after normalization. In our example, Straße becomes strasse, whereas lower() leaves its ß intact. These are different operations. CPython v3.12.4, str.casefold
A later operation can also break an earlier invariant. Our test starts with NFC ǰ (U+01F0). Case folding produces j plus a combining caron, which our interpreter reports as not NFC. Therefore the pipeline normalizes again after folding. It also allows whitespace runs to be collapsed with ' '.join(value.split()); that is an explicit application policy, not an additional Unicode normalization form.
With optional stages enabled, write this program’s transformation as:
where F is Python case folding and W is the stated whitespace operation. Disabled stages and their follow-up passes are omitted. The name search_policy in the demonstration is a label for this example, not a recommendation to overwrite every search document this way. The program does not claim to implement the separately specified NFKC_Casefold operation: for example, its test retains a soft hyphen in a\u00adb.
Measure collisions, then judge them
For a finite collection, let D be the set of distinct raw strings and K(D) its set of derived keys. We report:
For empty input the code reports zero by convention. Repeated copies of the same raw string do not enlarge D; a separate counter records them. On the 18 distinct strings in demo(), NFC produces 17 keys, NFKC produces 13, and NFKC plus case folding plus whitespace collapse produces 11. The respective fractions are 1/18, 5/18 and 7/18. These are results for the listed inputs, not population statistics or error rates.
Suppose each input in a finite task has a deterministic target label y(s). A classifier that sees only K(s) can reproduce all those labels only if every key class has one label:
Necessity follows because a deterministic classifier must return the same answer for the same key. Sufficiency follows by assigning each observed key its common label. Thus the number of collisions alone cannot tell us whether a policy is safe: we need the task’s distinctions. Conflicting labels for identical raw strings already violate the premise of a deterministic y(s).
A normalized fragment is not a safe concatenation unit
In our NFC counterexample, e is normalized and the combining acute accent alone is normalized. Their concatenation is not NFC: a pass over the whole string produces é.
where the double bar means concatenation. Normalizing each character independently fails for the same reason. The tests also include NFD/NFKD fragments whose combining marks need reordering across the boundary. This is why the implementation calls the library on whole strings. A streaming implementation would need a separate boundary strategy. UAX 15, §1.4
An auditable standard-library pipeline
Save the following complete program as text_normalization.py and run python3 text_normalization.py. This edition’s recorded run used Python 3.12.4 with Unicode database 15.0.0. The program prints the actual database version so a different interpreter is not silently described as the same environment. normalize, is_normalized and the database version are standard-library interfaces. CPython v3.12.4, unicodedata
The program accepts Unicode strings without surrogate code points, rejects unknown forms and non-Boolean switches, and can keep all transformations disabled. The normalization algorithm is supplied by Python; our implementation is the surrounding policy, trace, collision audit and counterexamples.
"""Original auditable text-normalization pipeline built on Python unicodedata.
Reports its actual Unicode database. Preserves raw text; does not implement the
Unicode algorithm from scratch, align arbitrary spans or solve confusables.
"""
import json
import unicodedata as ud
FORMS=('NFC','NFD','NFKC','NFKD')
def scalar_text(text):
if not isinstance(text,str):raise ValueError('A Unicode string is required')
if any(0xD800<=ord(c)<=0xDFFF for c in text):raise ValueError('Unpaired surrogate code points are not accepted')
return text
def options(form,fold,collapse):
if form is not None and form not in FORMS:raise ValueError('Choose None, NFC, NFD, NFKC or NFKD')
if type(fold) is not bool or type(collapse) is not bool:raise ValueError('Policy switches must be booleans')
def unicode_form(text,form='NFC'):
scalar_text(text)
if form not in FORMS:raise ValueError('Unknown Unicode normalization form')
return ud.normalize(form,text)
def pipeline(text,form='NFC',fold=False,collapse=False):
scalar_text(text);options(form,fold,collapse);stages=[]
def record(name,value):
stages.append({'operation':name,'text':value,'code_points':len(value),'utf8_bytes':len(value.encode('utf-8'))})
return value
value=record('input',text)
if form is not None:value=record(form,unicode_form(value,form))
if fold:
value=record('casefold',value.casefold())
if form is not None:value=record(form+' after casefold',unicode_form(value,form))
if collapse:
value=record('collapse whitespace',' '.join(value.split()))
if form is not None:value=record(form+' after whitespace',unicode_form(value,form))
return {'raw':text,'normalized':value,'changed':text!=value,'stages':stages,
'policy':{'form':form,'casefold':fold,'collapse_whitespace':collapse},'unicode_database':ud.unidata_version}
def key(text,form='NFC',fold=False,collapse=False):
return pipeline(text,form,fold,collapse)['normalized']
def audit(texts,form='NFC',fold=False,collapse=False):
texts=list(texts);options(form,fold,collapse);groups={};repeated=0
for text in texts:
normalized=key(text,form,fold,collapse);originals=groups.setdefault(normalized,[])
if text in originals:repeated+=1
else:originals.append(text)
distinct_raw=sum(len(values) for values in groups.values());distinct_keys=len(groups)
return {'input_rows':len(texts),'distinct_raw':distinct_raw,'distinct_keys':distinct_keys,'duplicate_raw_rows':repeated,
'collapsed_distinct_fraction':(distinct_raw-distinct_keys)/distinct_raw if distinct_raw else 0.,
'collisions':[{'key':k,'originals':v} for k,v in groups.items() if len(v)>1],
'idempotent_on_these_inputs':all(key(k,form,fold,collapse)==k for k in groups),
'scope':'Collision groups identify lost string distinctions, not whether the task permits losing them.'}
def character_report(text):
return [{'character':c,'code_point':f'U+{ord(c):04X}','name':ud.name(c,'<unnamed>'),'combining_class':ud.combining(c)} for c in scalar_text(text)]
def offset_example():
raw='Straße Café';normalized=key(raw,'NFC',True);target='Café'
a=raw.index(target);b=a+len(target);c=normalized.index(target.casefold());d=c+len(target.casefold())
return {'raw':raw,'normalized':normalized,'raw_codepoint_span':[a,b],'normalized_codepoint_span':[c,d],
'wrong_slice_if_reused':normalized[a:b],'correct_slice':normalized[c:d],
'scope':'This known target is relocated explicitly. Not a general character-offset aligner.'}
def demo():
samples=['Café','Cafe\u0301','①','1','ℝ','R','AI','AI','Straße','STRASSE','A\u00a0B','A B',' A\t B ','汉','漢','a','а','👩\u200d💻']
policies={'canonical':('NFC',False,False),'compatibility':('NFKC',False,False),'search_policy':('NFKC',True,True)}
left='e';right='\u0301';joined=unicode_form(left)+unicode_form(right)
split=''.join(unicode_form(c) for c in left+right)
forms={form:{'canonical_pair_equal':unicode_form('Café',form)==unicode_form('Cafe\u0301',form),
'circled_one':unicode_form('①',form),'compatibility_pair_equal':unicode_form('①',form)==unicode_form('1',form)} for form in FORMS}
fold_example='\u01f0';folded=unicode_form(fold_example).casefold()
return {'unicode_database':ud.unidata_version,'forms':forms,
'audits':{name:audit(samples,*config) for name,config in policies.items()},
'whole_string_counterexample':{'input':left+right,'characterwise':split,'whole':unicode_form(left+right),'equal':split==unicode_form(left+right)},
'concatenation':{'left_normalized':ud.is_normalized('NFC',left),'right_normalized':ud.is_normalized('NFC',right),'joined_normalized':ud.is_normalized('NFC',joined),'renormalized':unicode_form(joined)},
'casefold_requires_renormalization':{'before':fold_example,'folded':folded,'folded_is_nfc':ud.is_normalized('NFC',folded),'pipeline':key(fold_example,'NFC',True)},
'offset_example':offset_example(),'trace':pipeline(' Straße\tCafe\u0301 ','NFKC',True,True),
'unresolved_distinctions':{'latin_cyrillic_a_remain_different':key('a','NFKC')!=key('а','NFKC'),'simplified_traditional_remain_different':key('汉','NFKC')!=key('漢','NFKC')},
'characters':character_report('e\u0301👩\u200d💻'),
'scope':'Python standard-library implementation and original old-character examples. Not Unicode17 implementation conformance, locale-aware collation, tokenization, transliteration or automatic span repair.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2))
Read the trace before trusting an offset
The input Straße\tCafe\u0301 becomes strasse café under the demonstration’s broad policy. Each trace row retains its string, code-point length and UTF-8 byte length. These measures are different: our 👩\u200d💻 input has three code points and eleven UTF-8 bytes. This program does not count grapheme clusters or terminal display columns.
For Straße Café, the substring Café occupies code-point positions [7,11). After case folding, the corresponding café occupies [8,12). Reusing the old positions returns " caf", not the desired name. The example relocates a known target explicitly; searching for a substring is not a general alignment method, especially when a document repeats it.
For a span-bearing corpus, preserve raw text and its coordinate system. Then either annotate the transformed representation or store a validated mapping between versions. A transformation ledger helps diagnose changes but does not itself provide that mapping. Token offsets, UTF-8 byte offsets and Python code-point offsets must not be substituted for one another.
Cost and checks
Let m_j be the length at stage j and T(m_j) the library operation’s cost. With k recorded stages, total processing cost is the sum of those stage costs plus the cost of recording lengths and encodings. The trace retains O(sum m_j) characters; k is bounded by this program’s switches. We do not infer the library’s worst-case normalization complexity from a small timing measurement.
The collision audit deliberately favors inspectable lists for its 18 inputs. Membership checks within each collision group can require O(R²L) character comparisons in the worst case for R rows of length at most L, in addition to normalization. For a large corpus, retain the raw-to-key evidence while replacing this membership structure with sets or an external grouping job.
The original program has 15 focused tests, including composition exclusion, Hangul, invalid inputs, offset expansion, duplicated raw rows and fragment boundaries. A separate offline checker exercised unicode_form against the official Unicode 15.0.0 test file: 19,074 rows and the additional assigned-scalar checks specified in its report yielded 1,460,240 equalities. This verifies that wrapper in the recorded environment; it does not test the extra case/space policy or certify a Unicode 17 implementation. Official versioned test data
What this key cannot decide
The tests keep Latin a and Cyrillic а distinct, and keep simplified 汉 and traditional 漢 distinct. Visual resemblance and linguistic conversion require additional policies. The program neither transliterates scripts nor detects deceptive identifiers; accepting a string does not mean declaring it safe for a username.
Likewise, normalization does not recover incorrectly decoded bytes. If an import used the wrong encoding, changing code points afterward may leave the corruption intact. Preserve the input bytes and decode with an explicit format contract before applying this pipeline.
A useful comparison for a retrieval system is the untouched-string baseline, a canonical-key variant, and one explicitly broader policy. Measure query success and inspect newly merged groups with task labels. Preserve raw text for display and evidence. If normalization choices are tuned using evaluation results, separate development data from final testing, as in data leakage.
The demonstration’s observed idempotence is a finite check of its combined policy, not a proof for all possible Unicode strings or future databases. Freeze the interpreter, policy options and data version when a key becomes a stored identifier; a migration requires comparing old and new keys and resolving collisions.
Predict the lost distinction
-
Basic understanding. Must NFC merge
①and1? Which demonstrated form does merge them?Answer: No. Our NFC outputs remain different; NFKC and NFKD both output
1. Choose the equivalence needed by the task rather than assuming that a shorter output is cleaner. -
Hand calculation. Consider
['Café', 'Cafe\u0301', 'Café', '①', '1']. How many distinct raw strings and NFC keys are there? What does the audit’s fraction equal?Answer: Four distinct raw strings, three keys and one repeated raw row. The fraction is (4−3)/4=1/4, not 2/5. The duplicate does not create a new lost distinction.
-
Counterexample. Why is “normalize each arriving character, then append it” incorrect even if each character is individually NFC? Why does idempotence not rescue it?
Answer:
efollowed by U+0301 yields an uncomposed two-code-point string; normalizing the concatenation yieldsé. Idempotence concerns a second pass over an already normalized whole string. It does not say normalization distributes over concatenation. -
Method choice. A labeled mathematical corpus distinguishes
ℝfromR, and annotations refer to raw code-point spans. A proposed preprocessing job applies NFKC, case folding and whitespace collapse in place. What should the review require?Answer: Reject unexamined in-place replacement. The example merges the two mathematical strings, and other transformations can move spans. Retain raw strings and labels, audit collision groups, choose a task-specific derived key, and validate a coordinate mapping or re-annotate that representation. A lower distinct-key count is not evidence of better labels.
Versioned definitions and reproducible local evidence
This article uses UAX 15 revision 57 for its definitions and boundary warning, and the CPython v3.12.4 documentation for the actual interfaces. The standard’s version is Unicode 17.0.0; the recorded runtime database and official test data are 15.0.0. They are stated separately so reading a newer specification cannot be mistaken for running a newer implementation.
The tables, collisions, trace and offset failures are original computations on the program’s listed strings. The accompanying checks exercise the full program and retain negative results. Broader segmentation belongs in tokenization; evaluation design belongs in model evaluation.
Make a prediction, then check
Both pieces are NFC. Must their concatenation be NFC?
Learning objectives
- Choose canonical or compatibility keys using task distinctions.
- Explain collisions, idempotence and concatenation counterexamples.
- Preserve raw text, record policy and distinguish code-point from byte offsets.
- Run a version-reported pipeline and interpret its finite checks.
Prerequisites & connections
Explore related knowledge →References
- Unicode Standard Annex #15, revision 57
Ken Whistler; Unicode Consortium · 2025 - CPython v3.12.4 unicodedata documentation
Python documentation contributors · 2024 - CPython v3.12.4 str.casefold documentation
Python documentation contributors · 2024 - Unicode 15.0.0 NormalizationTest.txt
Unicode Consortium · 2022
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-08 · Codex single-AI-author technical check: scoped Unicode forms, pinned Python interfaces and official15.0 conformance data; six paired equations, raw/key distinction, finite collision and label-preservation reasoning, case/space policy, offset and concatenation failures, four explained exercises and computed SVGs. Actual runtime Python3.12.4/UCD15.0.0; not a Unicode17 implementation, general aligner or human peer review. Production browser acceptance recorded separately.
- Compared both manuscripts: canonical/compatibility keys, idempotence without task suitability, induced key equivalence and finite label recoverability, collision denominator excluding duplicated raw rows, declared extra policy and offset-coordinate distinction. Six paired equations, four explained exercises.
- Fifteen core/policy tests are embedded in production suite plus six publication checks. Unicode form table, composition exclusion/Hangul, casefold renormalization, invalid inputs, raw trace, fragment boundaries and the moved[7,11)→[8,12) span; distinct18 strings produce17/13/11 keys.
- Actual MDX unicode_form passed1,460,240 official15.0 equalities under Python3.12.4/UCD15.0.0. This does not cover the extra policy, arbitrary-sequence proof, Unicode17 implementation or third-party certification. Program does not implement NFKC_Casefold or a general span aligner.
- Four original SVGs bind actual output and raw data. Final isolated bilingual, three-width/four-font validation passed and desktop/mobile screenshots were inspected. Full article acceptance is recorded separately. Single-AI-author technical check, not independent human review; no upstream code copied or executed.
Source locations checked:
- Unicode Standard Annex #15, revision 57 · Scoped §§1.1–1.4, version and conformance discussion; Unicode 17 standard, not the Python 15.0 runtime. No full-standard or certification claim.
- CPython v3.12.4 unicodedata documentation · Pinned Doc/library/unicodedata.rst lines1–22 and99–149; database15.0, normalization and version interfaces.
- CPython v3.12.4 str.casefold documentation · Pinned stdtypes.rst lines1632–1648 only; casefold versus lower. Other policy behavior verified by original tests.
- Unicode 15.0.0 NormalizationTest.txt · Version header checked; full file consumed as offline conformance data, not manually reviewed row by row. Original checker and hashes retained; data not redistributed.
Related topics