Sub topic 2
Splitting Text: Whitespace and Regular Expressions
This chapter assumes you know basic Python (strings, lists, functions), the re module at the level of character classes, groups and quantifiers, and the difference between a token and a type from the previous chapter. You will build two tokenisers, compare them, and learn where each one fails.
What a tokeniser has to decide
A tokeniser takes one string and returns a list of tokens. To do this it must answer two questions for every character. Does this character belong to the current token? Does it start a new one?
The simplest answers use whitespace. More useful answers use patterns that describe what a token looks like. Every rule you write encodes a decision about language, so each choice has consequences for later steps such as counting types, stemming, or searching.
Splitting on whitespace
Python's str.split() with no argument splits on any run of whitespace and drops empty strings. It is fast and needs no setup.
text = "a b\n"
print(text.split(" "))
print(text.split())The first call returns ['a', '', 'b\n']. Splitting on a single space keeps empty strings and leaves the newline attached. The second call returns ['a', 'b']. In practice you almost always want the no-argument form.
Whitespace splitting has a clear weakness: it treats punctuation as part of the word next to it.
import re
text = "Don't split me naively, please."
print(text.split())
pattern = r"\w+(?:'\w+)?|[^\w\s]"
print(re.findall(pattern, text))The first print shows ["Don't", 'split', 'me', 'naively,', 'please.']. The tokens naively, and please. are different strings from naively and please. Counted as types, please. at the end of a sentence and please in the middle of one become two entries in the vocabulary. The second print shows ["Don't", 'split', 'me', 'naively', ',', 'please', '.']. Punctuation is now separate, and the contraction stays whole.
Reading the regular expression
The pattern \w+(?:'\w+)?|[^\w\s] has two alternatives separated by |:
\w+(?:'\w+)?matches one or more word characters, optionally followed by an apostrophe and more word characters. This keepsDon'ttogether.[^\w\s]matches exactly one character that is neither a word character nor whitespace. Each punctuation mark becomes its own token.
re.findall scans left to right and returns each non-overlapping match. Whitespace never matches either alternative, so it is skipped. This is the main design idea. You describe what a token is, and everything else is discarded. This is the opposite of split, where you describe the separators.
In Python 3, \w on a str is Unicode-aware. It matches letters and digits from any script, plus the underscore. So naïve is one token, but snake_case is also one token, because the underscore counts as a word character.
Building a tokeniser in stages
A real tokeniser grows by adding alternatives for token shapes you want to keep whole. Use re.VERBOSE so each alternative can carry a comment.
import re
TOKEN_RE = re.compile(r"""
https?://\S+?(?=[.,;:!?]*(?:\s|$)) # URLs, without trailing punctuation
| \d+(?:[.,]\d+)* # numbers such as 3,500.50
| \w+(?:[-']\w+)* # words, with inner hyphens or apostrophes
| [^\w\s] # any other single symbol
""", re.VERBOSE)
def tokenise(text):
return TOKEN_RE.findall(text)
sentence = ("Dr. Smith paid $3,500.50 for state-of-the-art tools "
"at https://example.com/a?b=1, didn't he?")
print(tokenise(sentence))The output is:
['Dr', '.', 'Smith', 'paid', '$', '3,500.50', 'for', 'state-of-the-art', 'tools', 'at', 'https://example.com/a?b=1', ',', "didn't", 'he', '?']Each alternative handles one case:
- The URL alternative uses a lazy quantifier,
\S+?, with a lookahead. The match stops as soon as what follows is optional punctuation and then whitespace or the end of the string. With a greedy\S+the comma afterb=1would be swallowed into the URL. - The number alternative keeps
3,500.50as one token, so the digits are not split around the comma and the full stop. - The word alternative allows a single hyphen or apostrophe between word characters.
state-of-the-artanddidn'tstay whole, but a trailing hyphen, as inpre- and post-war, is emitted as a separate symbol. - The last alternative is a catch-all. Without it, symbols such as
$would be silently dropped.
The tokeniser also gets one thing wrong. Dr. became Dr and ., which is wrong if you want the abbreviation kept intact.
Alternation order matters
Python tries alternatives from left to right and takes the first one that matches at the current position. It does not pick the longest match. If you put the word alternative before the number alternative, 3,500.50 would still work, because \w+ matches 3 and the number rule would never get a turn. That would produce 3, ,, 500, ., 50. Put the most specific shapes first and the general ones last. The catch-all must always come last.
import re
wrong_order = re.compile(r"\w+(?:[-']\w+)*|\d+(?:[.,]\d+)*|[^\w\s]")
print(wrong_order.findall("It cost 3,500.50 today"))This prints ['It', 'cost', '3', ',', '500', '.', '50', 'today']. The number rule is never reached.
Keeping character offsets
Many tasks need to know where a token came from: highlighting search hits, aligning labels, or mapping a result back to the source. Use finditer, which returns match objects with positions.
import re
pattern = re.compile(r"\w+(?:'\w+)?|[^\w\s]")
for m in pattern.finditer("Don't stop."):
print(m.start(), m.end(), m.group())This prints 0 5 Don't, 6 10 stop, and 10 11 .. The spans index into the original string, so text[m.start():m.end()] always recovers the token exactly. Keep this habit. Once you lowercase or rewrite tokens, the offsets are the only reliable link back to the source.
The tokeniser as a decision process
The diagram shows how the pattern from the previous section handles each position in the text.
Where these tokenisers fail
Even the staged tokeniser makes decisions you may not want. Here are the common errors.
- Abbreviations.
U.S.A.becomesU,.,S,.,A,.. A full stop can end a sentence or end an abbreviation, and a pattern cannot tell them apart without a list of known abbreviations or a trained model. - Curly apostrophes. The pattern above matches the straight apostrophe
'only. Text copied from word processors often has’, soDon’tbecomesDon,’,t. Either add’to the character class ([-'’]) or normalise quotation marks first. Normalisation is covered in a later chapter. - Clitics and possessives.
didn'tstays one token here. Some corpora, such as the Penn Treebank, split it intodidandn't. Neither is wrong, but your tokeniser must match whatever your downstream tools expect. - Hyphens.
state-of-the-artas one token makes sense.New York-basedas one token is less useful. A hyphen sometimes joins a compound and sometimes works as a dash. - Scripts without spaces. In Chinese and Japanese,
\w+matches an entire run of characters as a single token, because there are no spaces to stop it. Whitespace and regular-expression tokenisation cannot handle these languages. - Emoji and symbols.
[^\w\s]matches one code point at a time. An emoji built from several code points, such as a skin-tone variant or a family emoji, is split into pieces. - Social-media text. Hashtags (
#nlp), mentions (@user) and emoticons (:-)) are broken apart unless you add alternatives for them.
Choosing between the two approaches
| Approach | Strength | Weakness | Reasonable use |
|---|---|---|---|
| `str.split()` | One line, very fast | Punctuation stays attached to words | Quick checks, clean text already separated by spaces |
| Regex with `findall` | Explicit, tunable, easy to test | Rules grow complex, abbreviations remain hard | Domain-specific text, logs, prototypes |
| Library tokenisers (for example NLTK or spaCy) | Maintained rules for many edge cases | Less transparent, rules differ between libraries | General English text in production |
A regular-expression tokeniser is a good baseline. It is simple enough to read in full, and its failures are easy to trace to one rule. When the failures keep piling up, switch to a library tokeniser or a subword method rather than adding ever more alternatives.
Whichever you choose, count tokens and types on the same text with both tokenisers. A bad rule shows up directly as a larger vocabulary. A type count that jumps from 5,000 to 5,400 after a change means the new rule is creating fragments or separating forms that should match.
Exercise
The pattern \w+|[^\w\s] is used with re.findall on the string "Wait... what?!". List the tokens it produces, and explain why a pattern ending in [^\w\s]+ (with a plus sign) would give a different result.
Show answer
The tokens are ['Wait', '.', '.', '.', 'what', '?', '!']. The final alternative matches exactly one character, so each punctuation mark is its own token. With [^\w\s]+, runs of symbols stay together: the result would be ['Wait', '...', 'what', '?!']. Neither is universally correct. The first treats an ellipsis as three separate marks, while the second joins ?! into one token that will rarely appear elsewhere.
Exercise
You extend a tokeniser with the alternatives \w+(?:[-']\w+)*|\d+(?:[.,]\d+)*|[^\w\s], in that order. For the input "Version 2.5 is out", the number 2.5 comes out as 2, ., 5. What is wrong, and how do you fix it?
Show answer
Python takes the first alternative that matches at a position. At 2, the word alternative \w+(?:[-']\w+)* matches first, because digits are word characters, and it stops at the full stop. The number alternative is never tried. Move \d+(?:[.,]\d+)* before the word alternative so the more specific shape is tested first. The result is ['Version', '2.5', 'is', 'out'].