Sub topic 10
Putting the Steps in the Right Order
This chapter assumes you know basic Python strings, loops, list comprehensions, and functions. You should also understand that text can be represented as Unicode characters or as encoded bytes, and that tokenisation splits text into smaller units such as words.
Text cleaning is a pipeline: each step receives the output of the previous step. The order matters because a later step may depend on information that an earlier step changes.
A practical general-purpose order is:
- Decode bytes into text.
- Apply Unicode normalisation.
- Apply case folding.
- Optionally remove accents or diacritics.
- Clean whitespace.
- Tokenise.
- Remove stop words.
- Apply task-specific filtering.
If your input is already a Python str, decoding has already happened. If the input is raw UTF-8 data, decode it before any string operations.
Why the order matters
Consider stop words. A stop-word list containing "the" will not match the token "The" until case folding has changed it to lowercase-equivalent text. Likewise, a list containing "café" will not necessarily match a token written with a decomposed accent until both forms have been normalised consistently.
Punctuation also affects tokenisation. If punctuation is removed too early, you may lose useful information. For example, "can't" might become "cant", while a tokenizer designed for contractions might preserve it as "ca" and "n't" or as one token.
The following table shows the purpose of each stage.
| Stage | Typical operation | Main risk |
|---|---|---|
| Unicode normalisation | `NFC` or `NFKC` | Compatibility forms may discard distinctions |
| Case folding | `casefold()` | Case information is lost |
| Accent handling | Remove combining marks | Different words may become identical |
| Whitespace cleanup | Collapse repeated spaces | Formatting information is lost |
| Tokenisation | Split text into tokens | Token boundaries may be language-dependent |
| Stop-word removal | Filter common words | Negation or grammatical clues may disappear |
A pipeline that keeps its assumptions explicit
The code below uses NFKC, case folding, whitespace cleanup, tokenisation, and stop-word removal. The stop-word list is already written in the same normalised form as the tokens.
import re
import unicodedata
STOP_WORDS = {"the", "a", "an", "is", "of", "and", "to", "in"}
def normalise_text(text):
text = unicodedata.normalize("NFKC", text)
text = text.casefold()
text = re.sub(r"\s+", " ", text).strip()
return text
def tokenise(text):
return re.findall(r"\w+", text, flags=re.UNICODE)
def remove_stop_words(tokens):
return [token for token in tokens if token not in STOP_WORDS]
raw = "The Café is in the field"
clean_text = normalise_text(raw)
tokens = tokenise(clean_text)
content_tokens = remove_stop_words(tokens)
print(clean_text) # the café is in the field
print(tokens) # ['the', 'café', 'is', 'in', 'the', 'field']
print(content_tokens) # ['café', 'field']NFKC changes the typographic ligature fi into fi. Case folding makes matching consistent across scripts and cases. Whitespace cleanup happens before tokenisation so repeated spaces do not create accidental empty fields.
A second normalisation pass can be useful after transformations that introduce new character sequences. For strict, reusable pipelines, define one normalisation function and use it for both input text and configured word lists.
Choosing the pipeline for the task
There is no universally correct cleaning recipe. A search index may want "resume" and "résumé" to match, so accent stripping can help. A named entity recognition system may need accents and capitalisation to distinguish names. Sentiment analysis may need punctuation, repeated exclamation marks, and words such as "not".
Stop words need special care. Removing "not" can reverse the meaning of "not good". Removing "to" may be harmless for topic classification but harmful for a task that studies grammar or translation. Treat the stop-word list as a task-specific configuration, not as a permanent rule.
Checking whether steps undo one another
Test the pipeline with edge cases rather than only ordinary English sentences:
- Uppercase and lowercase variants.
- Composed and decomposed accents.
- Ligatures and full-width characters.
- Repeated whitespace.
- Negation, punctuation, and contractions.
- Names whose accents or capitalisation carry meaning.
- Stop words that occur inside longer tokens.
A useful invariant is that every configured stop word should pass through the same normalisation function as the input. Otherwise, filtering can fail silently.
Exercise
Why should case folding happen before stop-word removal, and why might accent stripping be skipped for named entity recognition?
Show answer
Case folding makes tokens such as "The" match a stop word stored as "the". Accent stripping might merge distinct names or remove information useful for identifying entities, so it should be applied only when the task allows that loss.