Normalize text by lowercasing, stripping accents and collapsing spaces

Why it matters Uncased BERT-style tokenizers, search engines and dedup pipelines all normalize Unicode before anything else.

Uncased tokenizers and search indexes first normalize text so 'Café', 'cafe' and 'CAFE' become the same string. Accents are removed by splitting each letter from its accent mark with Unicode decomposition and dropping the marks.

Write normalize_text(text). Apply Unicode NFKD normalization, remove every combining mark (unicodedata.combining(ch) is non-zero), lowercase, then collapse every run of whitespace into one space and strip both ends. Return the string.

Signaturedef normalize_text(text)

Example

normalize_text(' Café DÉJÀ vu ') is 'cafe deja vu'.

Understand the idea

Unicode can write the same letter in two ways: 'é' as one code point, or as 'e' followed by a combining acute accent. Normalization forms pick one way. NFD and NFKD decompose (split into base plus marks); NFC and NFKC compose. The K forms also map look-alike compatibility characters, such as full-width 'A', to plain 'A'.

Worked example: 'Café' in NFKD becomes 'C', 'a', 'f', 'e', plus a combining accent. Dropping the mark gives 'Cafe', and lowercasing gives 'cafe'. 'DÉJÀ' becomes 'deja' the same way. Collapsing spaces turns ' cafe deja vu ' into 'cafe deja vu'.

Rule: normalize(text) = collapse_spaces(lower(remove_marks(NFKD(text)))).

Uncased tokenizers, search indexes and near-duplicate filters for training data run this step first.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplenormalize_text(' Café DÉJÀ vu ')
  • Sample 2: mixed scripts and tabsnormalize_text('Naïve\tRésumé\n\nCoöperate')
  • Test 3: full-width lettersnormalize_text('\uff21\uff29 Model')
  • Test 4: already cleannormalize_text('plain text')