Sub topic 7
Cleaning Whitespace and Punctuation
Two strings can contain the same words and still differ in the characters between them. A no-break space is not a regular space. A curly apostrophe is not a straight one. This chapter covers how to find those differences, how to normalise them, and when to leave them alone.
This chapter assumes you know basic Python, regular expressions (re.sub, character classes), and the Unicode normalisation forms from the earlier chapters, especially NFKC. It also assumes you know what a token is.
Whitespace is a family of characters
In practice, "whitespace" means more than the space bar. Text scraped from web pages, PDFs, and word processors contains tabs, no-break spaces, thin spaces, ideographic spaces, and invisible characters. Python gives you two ways to ask whether a character counts as whitespace: str.isspace() and the \s class in re. For str patterns, both follow Unicode.
import re
import unicodedata
samples = {
"space": " ",
"tab": "\t",
"no-break space": "\u00a0",
"thin space": "\u2009",
"ideographic space": "\u3000",
"zero-width space": "\u200b",
"byte order mark": "\ufeff",
}
for name, ch in samples.items():
category = unicodedata.category(ch)
is_space = ch.isspace()
in_regex = re.match(r"\s", ch) is not None
print(f"{name:18} {category} {is_space!s:5} {in_regex}")The output shows the pattern:
| Character | Category | `isspace()` | Matched by `\s` |
|---|---|---|---|
| space | Zs | True | True |
| tab | Cc | True | True |
| no-break space (U+00A0) | Zs | True | True |
| thin space (U+2009) | Zs | True | True |
| ideographic space (U+3000) | Zs | True | True |
| zero-width space (U+200B) | Cf | False | False |
| byte order mark (U+FEFF) | Cf | False | False |
Zero-width space and byte order mark belong to category Cf (format characters). They render as nothing and \s does not match them. A pattern like re.sub(r"\s+", " ", text) therefore leaves them in place. The string "a\u200bb" prints as ab but has length 3 and does not equal "ab".
Which characters can you delete?
Not every invisible character is junk. Treat the three groups differently:
- Safe to delete in most NLP work: U+200B (zero-width space), U+2060 (word joiner), and U+FEFF (byte order mark or zero-width no-break space).
- Do not delete blindly: U+200C (zero-width non-joiner) and U+200D (zero-width joiner). Persian and several Indic scripts need them to spell words correctly. Many emoji sequences, such as family or profession emoji, are joined with U+200D.
- Control characters: Category Cc characters other than tab, newline, and carriage return (for example
\x00or\x1b) are almost always noise from broken extraction.
Collapsing whitespace
The usual goal is one space between tokens and no leading or trailing space. The function below removes the safe invisible characters, then collapses runs of whitespace. It has an option for keeping paragraph breaks, because newlines often carry structure that a later sentence splitter can use.
import re
ZERO_WIDTH = {ord(c): None for c in "\u200b\u2060\ufeff"}
def collapse_whitespace(text, keep_newlines=False):
text = text.translate(ZERO_WIDTH)
if keep_newlines:
text = re.sub(r"[^\S\n]+", " ", text) # horizontal whitespace, including \r
text = re.sub(r" ?\n ?", "\n", text) # no spaces around line breaks
text = re.sub(r"\n{3,}", "\n\n", text) # at most one blank line
return text.strip()
return re.sub(r"\s+", " ", text).strip()
raw = "Hello\u00a0 world\u200b!\r\n\r\n\r\n\tNext line\u3000here "
print(repr(collapse_whitespace(raw)))
print(repr(collapse_whitespace(raw, keep_newlines=True)))The first call prints 'Hello world! Next line here'. The second prints 'Hello world!\n\nNext line here'. The class [^\S\n] means "not a non-whitespace character and not a newline", which is a compact way to say "whitespace except newline".
If you run NFKC first, no-break, thin, and ideographic spaces already become plain spaces. The explicit zero-width removal is still needed, because NFKC has no mapping for those characters.
Punctuation: variants, then removal
Punctuation cleanup has two separate jobs. The first is unifying variants, so that one mark has one spelling. The second is removing marks you do not want.
Unifying variants
NFKC handles some variants. It turns the ellipsis character … into three full stops and converts full-width forms such as ! to !. It does not touch curly quotes or dashes. Those need an explicit mapping, which str.translate applies in a single pass.
PUNCT_MAP = str.maketrans({
"\u2018": "'", # left single quote
"\u2019": "'", # right single quote, also the typographic apostrophe
"\u201c": '"', # left double quote
"\u201d": '"', # right double quote
"\u2013": "-", # en dash, as in 1990-2000
"\u2014": " - ", # em dash, often written with no spaces around it
"\u2212": "-", # minus sign
})The apostrophe mapping matters most for English. A stop word list usually contains don't with a straight apostrophe. Text typed in a word processor contains don’t with U+2019. Without the mapping, the filter never matches those words.
The em dash maps to a dash with spaces on purpose. In panic—it's, replacing the dash with a bare hyphen would glue two words into panic-it's. Because this step can insert spaces, whitespace collapsing must run after it.
Removing punctuation
Three common approaches give different results. This snippet compares them:
import re
import string
import unicodedata
def remove_punctuation(text, replacement=""):
return "".join(
replacement if unicodedata.category(ch).startswith("P") else ch
for ch in text
)
sample = "Don\u2019t stop: it\u2019s 3.14, e-mail $5!"
print(remove_punctuation(sample))
print(re.sub(r"\s+", " ", remove_punctuation(sample, " ")).strip())
print(re.sub(r"[^\w\s]", "", sample))
print("\u2019" in string.punctuation)The four lines print:
Each approach has a different failure:
- Deleting punctuation merges
3.14into314ande-mailintoemail. If no space separates two sentences (end.Start), the two words fuse. - Replacing with a space keeps words apart but splits
Don’tintoDonandt, and3.14into3and14. [^\w\s]is short, but it also removes symbols such as$,+, and%, because those are not punctuation in Unicode. They are in category S. It also keeps the underscore, which counts as\w.string.punctuationcovers only 32 ASCII characters. It misses’,“,¿,¡,«, and。, so it is a poor choice for text that is not plain English.
Checking unicodedata.category(ch).startswith("P") works for any script. Chinese and Japanese full stops, Spanish inverted marks, and guillemets are all in the P categories.
Remove punctuation by tokenising, not by deleting
The cleanest answer for most pipelines is to avoid stripping punctuation as a separate step. Define what a token looks like and extract those. Internal apostrophes, internal hyphens, and decimal numbers stay inside tokens, and everything else drops out.
import re
import unicodedata
ZERO_WIDTH = {ord(c): None for c in "\u200b\u2060\ufeff"}
PUNCT_MAP = str.maketrans({
"\u2018": "'", "\u2019": "'", "\u201c": '"', "\u201d": '"',
"\u2013": "-", "\u2014": " - ", "\u2212": "-",
})
TOKEN_RE = re.compile(r"\d+(?:[.,]\d+)*|\w+(?:['\-]\w+)*")
def clean(text):
text = unicodedata.normalize("NFKC", text)
text = text.translate(ZERO_WIDTH).translate(PUNCT_MAP)
text = text.casefold()
return re.sub(r"\s+", " ", text).strip()
def tokenise(text):
return TOKEN_RE.findall(text)
raw = " \u201cDon\u2019t\u00a0panic\u201d\u200b\u2014it\u2019s 3.14,\te-mail me\u2026 "
cleaned = clean(raw)
print(cleaned)
print(tokenise(cleaned))The cleaned string is "don't panic" - it's 3.14, e-mail me.... The token list is ["don't", 'panic', "it's", '3.14', 'e-mail', 'me']. The quotes, the dash, the comma, and the trailing dots do not appear in any token, and the regular expression discarded them without a deletion step.
The first alternative in TOKEN_RE, \d+(?:[.,]\d+)*, takes whole numbers such as 3.14 or 1,000 before the word alternative can split them. This pattern suits English. German writes 3,14 and 1.000, and the pattern accepts both only because it allows either separator. It cannot tell them apart. Locale-specific number handling is a separate problem.
Putting the steps in order
The order below follows from what each step can produce.
- NFKC comes first because it converts many odd spaces and full-width punctuation into plain forms, so later steps handle fewer cases.
- The punctuation map comes before whitespace collapsing, because it can add spaces (the em dash).
- Whitespace collapsing comes last among the string steps, because earlier steps can leave doubled or leading spaces.
- Tokenising comes after cleaning so the token pattern sees consistent apostrophes and spaces.
Case folding can sit anywhere before tokenising. It does not interact with whitespace or punctuation.
When to keep whitespace and punctuation
Cleaning discards information. Decide per task:
| Task | Keep | Reason |
|---|---|---|
| Sentiment analysis | `!`, `?`, `...`, emoticons like `:)` | They carry tone. "Great." and "Great!!!" differ. |
| Named entity recognition | Periods in `U.S.` and `Dr.`, internal hyphens | They signal abbreviations and names. |
| Sentence splitting | Newlines and sentence-ending marks | Sentence splitters read them as boundaries. |
| Code, URLs, emails | Nearly everything | `@`, `/`, `_`, and `.` are part of the data. |
| Keyword search | Little | Fewer variants means more matches. |
If a later model uses its own tokeniser, such as a subword tokeniser trained on raw text, heavy cleaning can hurt by feeding it text unlike its training data. Normalise Unicode and obvious junk characters, then stop.
Exercise
A scraped string is "a\u200bb". You run re.sub(r"\s+", " ", text) on it and then compare the result to "ab". Does the comparison succeed? Explain, and say what fix you would use.
Show answer
No. U+200B is a format character (category Cf), not whitespace, so \s does not match it and re.sub leaves it in place. The result still has length 3 and is not equal to "ab". Fix it by removing the specific characters first, for example text.translate({0x200B: None}), or a translate table that also covers U+2060 and U+FEFF. Do not delete U+200C or U+200D without checking the language.
Exercise
Why does the clean() function map the em dash to " - " with spaces and then collapse whitespace afterwards, instead of collapsing first?
Show answer
The mapping can insert spaces. If the em dash became a bare hyphen, "panic—it's" would turn into "panic-it's", which the token pattern would keep as one word. The spaced version keeps the two words apart. Collapsing whitespace before the mapping would leave doubled spaces where the dash already had spaces on its sides, so collapsing must run after the punctuation map.
Exercise
You use re.sub(r"[^\w\s]", "", text) on product reviews and notice that "$5" becomes "5" and "50%" becomes "50". Which approach removes punctuation but keeps these symbols, and why does it work?
Show answer
Delete only characters whose unicodedata.category starts with "P". Currency signs like $ are in category Sc and the percent sign is Po, so check which one you need: $ is kept because it is a symbol (S), but % is punctuation (Po) and would still be removed. If you need % too, exclude it explicitly, or use a token pattern that keeps numbers with their symbols.