Sub topic 3
Where Simple Tokenisers Break
This chapter assumes you can write a basic Python function, read a regular expression, and name English grammar terms such as noun, plural and tense. Earlier chapters introduced tokens, types and two simple tokenisers: splitting on whitespace, and a regular expression that keeps contractions together and emits punctuation separately. Here you will push those tokenisers until they fail. You will see why each failure happens, and how real systems handle it.
Why failures matter
A tokeniser makes the first decision in an NLP pipeline, and later steps inherit that decision. If 3.50 becomes three tokens, a price extractor never sees a price. If [email protected] is broken into pieces, a search index cannot match the address. If a Chinese sentence becomes one giant token, the vocabulary fills with sentence-sized types that never repeat.
Tokenisation also has no single correct answer. Whether state-of-the-art is one token or four depends on the task. The aim is to choose rules deliberately and know what each rule costs.
Punctuation that is not punctuation
A period can end a sentence, or it can be part of an abbreviation (Dr.), a decimal number (3.50), a domain name (example.com) or an initialism (U.S.A.). The simple regular expression treats every period the same way, so it splits all of these.
import re
naive = r"\w+(?:'\w+)?|[^\w\s]"
text = "Dr. Smith paid $3.50 for the e-mail."
print(text.split())
print(re.findall(naive, text))['Dr.', 'Smith', 'paid', '$3.50', 'for', 'the', 'e-mail.']
['Dr', '.', 'Smith', 'paid', '$', '3', '.', '50', 'for', 'the', 'e', '-', 'mail', '.']The two tokenisers fail in opposite ways. Whitespace splitting leaves the final period glued to e-mail., so e-mail. and e-mail become different types. The regular expression separates that period correctly, but it also cuts the price into $, 3, . and 50, and it splits Dr. from its dot.
The decision about a single period can be written as a short flow of questions. Real tokenisers encode a version of it as ordered rules or as a trained classifier.
A rule-ordered tokeniser
You can fix many of these cases by listing patterns from most specific to most general. Python's regular-expression engine tries alternatives left to right at each position and takes the first that matches. Specific patterns such as URLs must therefore come before the general word pattern.
import re
PATTERNS = [
r"https?://\S+[^\s.,;:!?)\]]", # URLs, without trailing punctuation
r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+", # email addresses
r"\$?\d+(?:[.,]\d+)*%?", # numbers, prices, percentages
r"\b(?:Dr|Mr|Mrs|Ms|Prof)\.", # known abbreviations
r"\w+(?:[-'’]\w+)*", # words with inner hyphens or apostrophes
r"[^\w\s]", # any other single symbol
]
TOKEN_RE = re.compile("|".join(PATTERNS))
def tokenise(text):
return TOKEN_RE.findall(text)
samples = [
"Dr. Smith paid $3.50 for the e-mail.",
"Don't use state-of-the-art tools.",
"Visit https://example.com/a?b=1 or mail [email protected].",
"It cost 12,000 dollars, or 15% more.",
]
for sample in samples:
print(tokenise(sample))['Dr.', 'Smith', 'paid', '$3.50', 'for', 'the', 'e-mail', '.']
["Don't", 'use', 'state-of-the-art', 'tools', '.']
['Visit', 'https://example.com/a?b=1', 'or', 'mail', '[email protected]', '.']
['It', 'cost', '12,000', 'dollars', ',', 'or', '15%', 'more', '.']Every group in the patterns is non-capturing ((?:...)). That matters, because re.findall returns only the captured groups when a pattern contains capturing groups, which silently corrupts the output.
This tokeniser still has gaps, and you should know them before you trust it:
- The abbreviation list is closed.
Gen.orSt.is split into a word and a period. - A real sentence-ending
Dr.(as in "I asked the Dr.") keeps its period, so the sentence boundary is lost. 3rdbecomes3andrd, because the number pattern matches first. Reordering the patterns would fix that case and break others.U.S.A.becomesU,.,S,.,Aand..
Contractions
English contractions fuse two grammatical words into one written form. The simple regular expression keeps don't whole, which is convenient for counting but hides the negation from any later step that wants to know that the verb is do and the particle is not.
The Penn Treebank convention, which many parsers and taggers were trained on, splits contractions into their grammatical parts. NLTK implements it as TreebankWordTokenizer, which needs no extra downloads.
from nltk.tokenize import TreebankWordTokenizer
tokenizer = TreebankWordTokenizer()
print(tokenizer.tokenize("I'm sure they don't know."))['I', "'m", 'sure', 'they', 'do', "n't", 'know', '.']Note the split points: do + n't, not don + 't. The convention follows the grammar, not the spelling. The same rule turns can't into ca + n't, so ca becomes a token that is not a dictionary word. If a downstream tool was trained on Treebank-style tokens, use this convention. If you simply count words for a classifier, keeping don't whole is often fine. Pick one convention and apply it to training data and live data alike.
Hyphens and dashes
A hyphen has at least three jobs, and the same character serves all of them:
| Use | Example | Reasonable handling |
|---|---|---|
| Compound word | `e-mail`, `state-of-the-art` | Keep as one token, or split into parts |
| Range or relation | `2020-2024`, `Paris-London` | Usually split |
| Line-break hyphenation | `tokeni-` then `sation` on the next line | Rejoin before tokenising |
Keeping hyphenated compounds whole shrinks token counts but grows the vocabulary: well-known, well-established and well-documented are three unrelated types, and each appears rarely. Splitting them gives the model more shared parts but loses the compound meaning. Search engines often index both forms.
Typography adds further variants. Writers also use the en dash (–), the em dash (—) and the non-breaking hyphen (‑, U+2011). A pattern that only allows ASCII - treats them all as separate symbols, so normalise them first or list them explicitly in the pattern.
Languages without spaces
English-style splitting assumes that spaces separate words. Chinese and Japanese are written without spaces between words. Thai is written without spaces between words and uses spaces mainly between phrases or sentences. Whitespace splitting returns the whole sentence as one token. A \w+ regular expression does no better, because Python treats CJK characters as word characters.
import re
text = "我喜欢自然语言处理" # "I like natural language processing"
print(text.split())
print(re.findall(r"\w+", text))
print(list(text))['我喜欢自然语言处理']
['我喜欢自然语言处理']
['我', '喜', '欢', '自', '然', '语', '言', '处', '理']The first two results are one nine-character token. The third splits into single characters, which is a valid tokenisation, since many Chinese words are one or two characters long. Character tokens never run out of vocabulary, but they are short and individually ambiguous, so a model needs more context to recover meaning.
The proper alternative is word segmentation, which decides where word boundaries fall. The usual approaches are dictionary lookup with a search for the most probable split, or a trained sequence model that labels each character as the start, middle or end of a word. Libraries such as jieba for Chinese and MeCab for Japanese do this. Segmentation errors then become tokenisation errors, and segmenters disagree on borderline cases, so the same sentence can have more than one defensible split.
Spaces do not guarantee word boundaries in other languages either. German forms long compounds, such as Donaudampfschifffahrtsgesellschaft (Danube steamship company). Whitespace splitting treats that as one rare type, even though its parts are common words. Finnish and Turkish pack many suffixes into a single written word, so a single word can carry meaning that English spreads over a phrase.
Detecting problems in your own data
Do not rely on a few hand-picked sentences. Run the tokeniser over a sample of the real corpus and inspect the tokens it produces:
- List the most frequent single-character tokens. Unexpected letters or digits suggest broken words or numbers.
- List tokens that contain punctuation. Check that they are intentional (URLs, prices) and not leftovers.
- Look at the rarest types. Many strange hapax tokens (types that occur once) often mean a missed rule.
- Compare the number of tokens and types before and after a rule change.
What comes next
Rules can cover only the cases their author thought of, and any new domain, with its hashtags, chemical names or code snippets, brings new ones. Languages that need segmentation cannot be handled by punctuation rules at all. Subword tokenisation, covered later in this tutorial, takes a different route: it learns frequent fragments from data, so unseen strings can still be represented from smaller known pieces.
Exercise
The rule-ordered tokeniser turns "3rd" into "3" and "rd". Which of the six patterns causes this, and how would you change that pattern so "3rd" stays whole while "3.50" and "15%" still work?
Show answer
The number pattern, r"\$?\d+(?:[.,]\d+)%?", matches "3" first, and then the word pattern matches "rd". One fix is to add an optional alphabetic suffix, for example r"\$?\d+(?:[.,]\d+)(?:%|(?:st|nd|rd|th)\b)?". With this change "3rd" is one token and "3.50" and "15%" are unchanged. You must still re-run all earlier test sentences, because this edit changes what the pattern can match.
Exercise
A colleague tokenises Chinese product reviews with text.split() and finds a vocabulary of 90,000 types where almost every type occurs once. Explain why this happens and name two better options.
Show answer
Chinese has no spaces between words, so split() returns whole clauses or sentences as single tokens. Each review is nearly unique, so almost every type occurs once, and the vocabulary is useless for counting or learning. Better options are character-level tokens (list(text)), a dedicated word segmenter such as jieba, or a learned subword tokeniser.