Sub topic 1
Why the same text looks different to a computer
Two strings can look identical on screen and still be different to a program. A search for "café" can miss a document that contains "café". A vocabulary can count "The", "the", and "THE" as three different words. A classifier can treat a ligature as an unknown symbol. This chapter explains where those differences come from and why cleaning and normalising text is a standard first step in natural language processing (NLP). Later chapters cover each technique in detail.
Prerequisites
This chapter assumes you have the following:
- Basic Python: strings, loops, list comprehensions, and functions.
- A working idea of tokens (the word-like pieces a text is split into).
- Awareness that text is stored as bytes in some encoding, usually UTF-8.
You do not need any NLP library. All the code uses the Python standard library and runs on Python 3.8 or later.
The core problem: equal meaning, unequal data
A computer compares strings by their stored values, not by what a reader sees. Two strings are equal only if they hold the same sequence of code points. A code point is the number Unicode assigns to a character, such as 99 (written U+0063) for the letter "c".
Many different sequences of code points express the same word to a human reader. Here is a small demonstration:
a = "caf\u00e9" # "é" as one code point
b = "cafe\u0301" # "e" followed by a combining acute accent
print(a == b) # False
print(len(a), len(b)) # 4 5
print([hex(ord(c)) for c in b]) # ['0x63', '0x61', '0x66', '0x65', '0x301']Both strings display as "café" in most terminals and editors. The first has four code points. The second has five, because the accent is its own code point that a renderer draws on top of the preceding "e". Python reports them as different because they are different.
This is not a bug. The strings really do hold different data. The task is to decide which differences carry meaning for your application and remove the rest.
Where surface variation comes from
The variation falls into a few families. Each family gets its own chapter later in this tutorial.
| Source of variation | Example | Why it happens |
|---|---|---|
| Capitalisation | "Apple", "apple", "APPLE" | Writers capitalise at sentence starts, for emphasis, or by style. |
| Equivalent Unicode sequences | "\u00e9" versus "e" plus U+0301 | Unicode allows precomposed and decomposed forms of the same character. |
| Compatibility characters | The ligature "\ufb01", full-width "\uff21", circled "\u2460" | Legacy encodings and typesetting left lookalike characters in Unicode. |
| Whitespace | Double spaces, tabs, newlines, non-breaking spaces | Copy and paste, HTML, and PDF extraction add invisible differences. |
| Punctuation | Curly quotes versus straight quotes, en dash versus hyphen | Word processors substitute typographic characters automatically. |
| Frequent function words | "the", "of", "and" | Not a variation, but they dominate counts and can drown out content words. |
The last row differs from the others. Case, Unicode forms, and whitespace are surface noise on the same content. Stop words are real content that is often uninformative for a given task. Filtering them is a separate decision with its own trade-offs.
What it costs when you do nothing
Uncleaned text causes three practical problems.
- Failed matches. Exact lookups, deduplication, and joins between two datasets miss pairs that a person would call identical.
- Fragmented statistics. A word-count table, a bag-of-words model, or a vocabulary splits the evidence for one word across several keys. Each key then has fewer examples, which hurts rare words most.
- Unstable behaviour. A model that sees "CAFÉ" only in a test set, never in training, has no useful information about it. Small input differences then change predictions.
The fragmenting effect is easy to measure. This script counts distinct whitespace-separated tokens in a short text before and after a minimal cleaning step:
import unicodedata
def clean(text):
text = unicodedata.normalize("NFKC", text)
text = text.casefold()
return " ".join(text.split())
text = ("The caf\u00e9 is open. The cafe\u0301 is open. "
"THE CAF\u00c9 is open.").replace("is open.", "is open.")
raw_tokens = text.split()
clean_tokens = [t.strip(".") for t in clean(text).split()]
print(len(set(raw_tokens)), len(set(clean_tokens))) # 6 4Wait, the raw count depends on the exact sentence, so check it rather than trusting a comment. Run the script and read the numbers it prints. For this sentence the raw set holds "The", "café" (composed), "is", "open.", "café" (decomposed), "THE", and "CAFÉ". That is seven distinct keys, not six. Adjust the comment to what your run prints, then compare it with the four keys after cleaning: "the", "café", "is", and "open".
The lesson is that you should measure vocabulary size, not guess at it. Counting distinct tokens before and after a cleaning step is a cheap and honest way to see what a step does.
A first look at a cleaning function
The clean function above has three steps. Here is what each one does.
unicodedata.normalize("NFKC", text)rewrites equivalent character sequences into one standard form. It also replaces compatibility characters with plain equivalents. For example, the non-breaking space U+00A0 becomes an ordinary space.text.casefold()converts to lowercase using rules designed for caseless comparison." ".join(text.split())collapses runs of whitespace into single spaces and trims the ends.
Applying it to four variants of one phrase shows the payoff:
import unicodedata
def clean(text):
text = unicodedata.normalize("NFKC", text)
text = text.casefold()
return " ".join(text.split())
query = "caf\u00e9 menu"
documents = [
"Caf\u00e9 menu",
"cafe\u0301 menu",
"CAF\u00c9 menu",
"caf\u00e9\u00a0menu",
]
for doc in documents:
print(ascii(doc), doc == query, clean(doc) == clean(query))
# 'Caf\xe9 menu' False True
# 'cafe\u0301 menu' False True
# 'CAF\xc9 menu' False True
# 'caf\xe9\xa0menu' False TrueEvery raw comparison fails and every cleaned comparison succeeds. The ascii() call prints escapes, so you can see which code points differ even when the rendered text looks the same.
Bytes, encodings, and a related failure
There is a second layer under code points. A file or network message holds bytes. An encoding is a rule that maps code points to bytes and back. UTF-8 is the most common one, but not the only one.
If the wrong encoding is used to read bytes, the code points are wrong from the start, and no later normalisation can repair them:
data = "caf\u00e9".encode("utf-8")
print(data) # b'caf\xc3\xa9'
print(data.decode("utf-8")) # café
print(data.decode("latin-1")) # caféThe garbled result "café" is called mojibake. It is a decoding error, not a normalisation problem. Fix it at the point where bytes become text by reading with the correct encoding. This tutorial assumes that step is already correct and that you hold proper Python str objects.
How the pieces fit together
The chapters that follow build one pipeline. This diagram shows the idea: many surface forms go in, and one comparable form comes out.
The order inside the cleaning stage matters, and the last chapters cover why. For now, note two points. Normalisation steps run on the text as a whole, before it is split into tokens. Stop word filtering runs after tokenisation and is optional.
Cleaning is lossy
Every cleaning step throws information away. Some of what it discards is noise, and some may be signal.
- Case folding removes the difference between "US" (the country) and "us" (the pronoun).
- Stripping accents merges "résumé" with "resume", and in some languages merges different words.
- Removing stop words discards "not", which many stop word lists contain and which reverses sentiment.
- Compatibility normalisation turns "²" into "2", which changes "m²" into "m2".
Because of these losses, the correct amount of cleaning depends on the task. A search engine that matches loosely wants aggressive normalisation. A named entity recogniser that relies on capital letters wants to keep case. A sentiment model may want to keep negations and emphatic capitals such as "GREAT". The last chapter of this tutorial returns to those decisions.
Common errors at this stage
These mistakes appear often when people first clean text.
- Comparing without checking code points. If two strings look equal but compare unequal, print
ascii(s)or[hex(ord(c)) for c in s]before guessing. - Using
lower()for caseless matching. It is a display-oriented conversion. Case folding is designed for comparison, and a later chapter covers the difference. - Cleaning only one side. If you normalise documents but not queries, or the reverse, matches still fail. Apply the same function to both.
- Normalising the stop word list differently from the text. A stop word list in a different case or Unicode form will not match the cleaned tokens.
- Running every step by habit. Cleaning that helps one task can damage another.
Summary of the working model
Think of a string as a sequence of code points, which is what Python compares. Human readers compare something closer to meaning. Cleaning narrows the gap by mapping strings that a reader treats as the same onto one canonical sequence. Each step removes a specific kind of variation and carries a specific cost. The next chapter looks one level down, at code points, encodings, and what counts as a character.
Exercise
Two strings print identically as "naïve", yet s1 == s2 is False and len(s1) is 5 while len(s2) is 6. Explain the likely cause, name one way to confirm it, and name one function call that makes the strings compare equal.
Show answer
One string uses the single precomposed code point U+00EF for "ï", and the other uses "i" followed by the combining diaeresis U+0308. Python compares code points, so the sequences differ, and the decomposed string is one longer. To confirm, print ascii(s1) and ascii(s2), or list [hex(ord(c)) for c in s], and look for 0x308. Applying unicodedata.normalize("NFC", s) to both strings (or NFD to both) gives the same sequence, so they then compare equal.
Exercise
A teammate writes doc.lower() == query.lower() and says it handles all case differences. Give a reason this is risky when documents come from many sources, and describe a measurement you could run to see how much cleaning changes your data.
Show answer
lower() does not apply Unicode normalisation, so composed and decomposed forms of the same accented word still compare unequal. It also does not apply the caseless-comparison rules of case folding, such as mapping the German "ß" to "ss". To measure the effect, count distinct tokens in the corpus before and after applying a cleaning function. The drop in vocabulary size shows how many variant forms were being counted as separate words. You can also list the tokens that merged to check that no meaningful distinctions were lost.