Sub topic 7
Cleaning Whitespace and Punctuation
This chapter assumes you know basic Python strings, loops, functions, and list comprehensions. It also assumes you know that text can contain Unicode characters and that tokenisation divides text into usable pieces such as words.
Whitespace and punctuation are useful to readers, but they can create unwanted variation for a natural language processing system. These strings contain the same words:
"Natural language processing"
"Natural language processing"
"Natural\nlanguage\tprocessing"A model or search system may treat them differently unless you clean them consistently.
Normalising whitespace
Whitespace includes ordinary spaces, tabs, and line breaks. The regular expression token \s matches common whitespace characters. The + means “one or more”, so \s+ matches a whole run of whitespace.
A reliable first step is to replace each run with one ordinary space and remove spaces at the ends:
import re
def normalise_whitespace(text):
return re.sub(r"\s+", " ", text).strip()
raw = " Natural \n language\tprocessing "
cleaned = normalise_whitespace(raw)
print(cleaned)
# Natural language processingThis operation does not remove meaningful words. It only removes formatting variation. It is usually safe for search indexes, document classification, and many other text-processing tasks.
Whitespace can be meaningful in some data. For example, indentation in source code or line breaks in poetry should not be flattened without considering the task.
Cleaning punctuation
Punctuation is any character used to mark structure or boundaries, such as commas, full stops, quotation marks, brackets, and dashes. Unicode contains many punctuation characters, including curly quotation marks and em dashes.
Python's string.punctuation contains only a fixed set of ASCII punctuation characters. It does not cover every Unicode punctuation mark. The unicodedata module provides a better general test. A character whose Unicode category starts with P is punctuation.
Before removing punctuation, decide what the task needs:
| Goal | Typical action | Main risk |
|---|---|---|
| Count words | Replace punctuation with spaces | Removing boundaries can join words |
| Exact or phrase search | Use a documented punctuation policy | Different policies produce different matches |
| Sentiment analysis | Keep `!`, `?`, or punctuation features | Punctuation can affect sentiment |
| Named entity recognition | Usually preserve original punctuation | Punctuation can identify names and locations |
Replacing punctuation with a space is often safer than deleting it. For example, deleting the hyphen in state-of-the-art produces stateoftheart, while replacing it produces separate words.
import re
import unicodedata
def normalise_whitespace(text):
return re.sub(r"\s+", " ", text).strip()
def punctuation_to_spaces(text, keep=frozenset({"'", "’"})):
result = []
for character in text:
category = unicodedata.category(character)
if category.startswith("P") and character not in keep:
result.append(" ")
else:
result.append(character)
return "".join(result)
def clean_for_word_count(text):
text = punctuation_to_spaces(text)
return normalise_whitespace(text)
raw = "State-of-the-art models—really?—can work."
cleaned = clean_for_word_count(raw)
print(cleaned)
# State of the art models really can work.The keep set preserves straight and curly apostrophes. This lets a later tokeniser keep words such as can't together. You could instead replace apostrophes with spaces if your application treats can and t as separate tokens.
Clean before tokenising
Cleaning and tokenising interact. If you delete punctuation before tokenising, you may accidentally join two words. If you tokenise first, punctuation may become separate tokens that you must handle later.
A simple word tokeniser can preserve apostrophes inside words:
import re
def tokenise_words(text):
return re.findall(r"\w+(?:['’]\w+)*", text, flags=re.UNICODE)
text = "Clean text—then tokenise it, carefully."
print(tokenise_words(text))
# ['Clean', 'text', 'then', 'tokenise', 'it', 'carefully']The expression \w+ matches a sequence of word characters. The optional part (?:['’]\w+)* allows an apostrophe followed by more word characters. This is a practical rule, not a complete linguistic tokeniser. Languages with different word-boundary rules may need specialised tools.
Check the result against the task
A cleaning function should have a clear contract. Document whether it lowercases text, preserves apostrophes, replaces punctuation with spaces, or removes it. Apply the same policy to training data and later input.
For example, a search system might remove commas but preserve hyphens in product codes. A sentiment system might preserve ! because repeated exclamation marks can carry a signal. A named entity recognition system often benefits from seeing the original punctuation.
Test edge cases before using a cleaner on a large collection:
- Multiple spaces, tabs, and line breaks.
- Curly quotes and Unicode dashes.
- Apostrophes in contractions.
- Hyphens between words.
- Decimal numbers such as
3.14. - Empty strings and strings containing only punctuation.
Exercise
Why should punctuation usually be replaced with a space instead of simply deleted?
Show answer
Deleting punctuation can join neighbouring words. Replacing it with a space preserves their boundary, so "high-quality" can become "high quality" instead of "highquality".