Sub topic 11
When Not to Clean: Trade-offs by Task
Assume you know Python strings, functions, list comprehensions, and the idea of tokens. This chapter focuses on choosing which cleaning steps to use. Cleaning text is useful because it reduces surface variation. However, every cleaning step can also remove information.
A good pipeline does not make text “as simple as possible.” It keeps the information that the task needs and removes only irrelevant variation.
Cleaning can improve one task and damage another
Case folding, accent stripping, punctuation removal, and stop word removal all change the input. The change may help a search system match more documents. It may harm a sentiment model that needs punctuation or a named entity recognition system that needs exact spelling.
For example, these strings may refer to different things:
Applecan mean the company or the fruit.USandushave different meanings.good!!!expresses stronger emotion thangood.résuméandresumemay be treated as equivalent in a broad search, but not in a spelling-sensitive application.New Yorkcontains a space that helps identify one place name.
The right question is not “How do I clean this text?” Ask instead: “Which differences matter for this task?”
| Task | Often useful | Use with caution or skip |
|---|---|---|
| Broad keyword search | Case folding, NFC or NFKC, whitespace cleanup | Accent stripping when accents distinguish words |
| Sentiment analysis | Case folding, Unicode cleanup, careful whitespace cleanup | Stop word removal, punctuation removal, emoji removal |
| Named entity recognition | Unicode normalization, limited whitespace cleanup | Accent stripping, aggressive punctuation removal, lowercasing |
| Exact identifiers | Unicode validation and a documented form | Case folding, accent stripping, stop word removal |
| Topic classification | Case folding, tokenization, selected stop word removal | Removing negations such as “not” |
Sentiment analysis: preserve signals
Sentiment analysis predicts an attitude or emotion in text. Words are important, but punctuation, capitalization, negation, and emoji can also carry sentiment.
Removing stop words may remove a negation:
not usefulIf not is removed, the remaining word suggests the opposite meaning. Removing exclamation marks can also make these two inputs look identical:
This is great!
This is greatA safe starting point is to apply Unicode normalization, case folding, and whitespace cleanup. Keep punctuation, emoji, and words such as not, never, and without unless experiments show that a model does not need them.
A tokenizer designed for the model may represent !!!, emoji, or contractions more effectively than a simple regular expression. Cleaning should not replace task-appropriate tokenization.
Named entity recognition: preserve spelling and boundaries
Named entity recognition, or NER, finds entities such as people, organizations, locations, and dates. The exact form of a name often provides useful evidence.
Consider:
Dr. María de los Ángeles joined ACME, Inc.Removing accents can turn María into Maria. Lowercasing can remove a useful clue about proper names. Removing punctuation can turn ACME, Inc. into a different sequence of tokens. Removing spaces can damage multiword names.
Unicode normalization is usually safer than accent stripping. Normalize equivalent Unicode sequences, but retain the letters, case, punctuation, and word boundaries that identify entities. If a model requires lowercase input, preserve the original text separately so that predictions can be mapped back to the source.
Search: match recall against precision
Search systems often benefit from normalizing queries and documents in the same way. Case folding lets Python match python. Compatibility normalization can make full-width forms match ordinary forms. Whitespace cleanup reduces accidental mismatches.
Accent stripping can improve recall. A user who types cafe may expect results containing café. However, it can reduce precision in languages where accents distinguish words. A search system can store both the original and an accent-insensitive field, then choose how strongly to use each field.
The most important rule is consistency. Apply the same relevant transformation to the query and the indexed text. Do not normalize only one side.
A task-dependent decision process
Use this sequence when designing a pipeline:
flowchart TD
A[Start with raw text] --> B{Does the difference affect the task?}
B -->|No| C[Normalize or remove it]
B -->|Yes| D[Preserve it]
C --> E{Must query and document forms match?}
E -->|Yes| F[Apply the same pipeline to both]
E -->|No| G[Validate the result]
D --> G
G --> H[Test with representative examples]
H --> I[Keep the original text for recovery]First, identify the information your model or search rule uses. Next, test one transformation at a time. Compare results on examples that include accents, capitalization, punctuation, negation, emoji, and multiple-word names.
Do not assume that a smaller vocabulary means a better system. Stop words may be unhelpful for a topic model but essential for sentiment. Lowercase text may simplify classification but remove a useful feature for NER. Accent stripping may help a tolerant search field but should not replace the canonical value.
A practical comparison
The following code compares an aggressive pipeline with a conservative one. The aggressive version is suitable only when the task allows information loss.
import re
import unicodedata
text = "Dr. María said: This is NOT good!!!"
def conservative(text):
text = unicodedata.normalize("NFC", text)
text = text.casefold()
return re.sub(r"\s+", " ", text).strip()
def aggressive(text):
text = unicodedata.normalize("NFKD", text)
text = "".join(
ch for ch in text
if not unicodedata.combining(ch)
)
text = text.casefold()
text = re.sub(r"[^\w\s]", " ", text)
text = re.sub(r"\s+", " ", text).strip()
return text
print(conservative(text))
print(aggressive(text))The conservative result keeps punctuation and the word not. The aggressive result removes the accent and punctuation. It may help broad matching, but it is a poor default for sentiment or NER.
Exercise
You are building a sentiment classifier. Which should you preserve: the word "not", exclamation marks, or neither? Why?
Show answer
Preserve both by default. "Not" changes polarity, and exclamation marks can express emphasis. Test later whether the model benefits from keeping them.