Sub topic 2
Splitting Text: Whitespace and Regular Expressions
Prerequisites and the goal
This chapter assumes you know basic Python, including strings, lists, and regular expressions. You should also know the basic idea of an NLP task such as search or classification.
Tokenisation is the process of dividing text into smaller units called tokens. A token might be a word, punctuation mark, number, or other meaningful piece. Tokenisation is often the first step before counting words, searching text, or creating model features.
A token is an occurrence in a piece of text. A type is a distinct token value. For example, in:
the dog saw the dogthere are five tokens but four types: the, dog, saw, and the? More precisely, the distinct types are the, dog, and saw, so there are three types. The repeated word the and dog each occur more than once.
| Text | Number of tokens | Number of types |
|---|---|---|
| `the dog saw the dog` | 5 | 3 |
The number of tokens measures the length of the text. The number of types measures the size of its observed vocabulary.
Splitting on whitespace
The simplest tokeniser splits whenever it finds whitespace. In Python, str.split() handles spaces, tabs, and line breaks:
text = "NLP uses text data.\nIt can be useful."
tokens = text.split()
print(tokens)
print(len(tokens))Output:
['NLP', 'uses', 'text', 'data.', 'It', 'can', 'be', 'useful.']
8This method is fast and often useful for quick experiments. However, it treats punctuation as part of a neighbouring token. data. and data become different strings. The same problem occurs with commas, quotation marks, and parentheses.
Whitespace splitting also produces surprising results for contractions and hyphenated words:
text = "Don't re-use this well-known method."
print(text.split())The result contains Don't, re-use, and method. as whole tokens. Whether that is correct depends on the task. A search system may want punctuation separated. A language model may need a different tokenisation scheme.
Regular-expression tokenisation
A regular expression, or regex, describes text patterns. A regex tokeniser can recognise word-like text and punctuation separately.
import re
text = "Don't split me naively, please."
pattern = r"\w+(?:'\w+)?|[^\w\s]"
tokens = re.findall(pattern, text)
print(tokens)Output:
["Don't", 'split', 'me', 'naively', ',', 'please', '.']The pattern has two alternatives:
\w+(?:'\w+)?matches one or more word characters, with an optional apostrophe and more word characters. This keepsDon'ttogether.[^\w\s]matches one character that is neither a word character nor whitespace. This captures punctuation such as,and..
The re.findall() function returns every non-overlapping match in order. This makes it convenient for a small, task-specific tokeniser.
A regex can also handle numbers differently if the application needs to preserve decimals, dates, or currency values. For example, a general pattern might need separate rules for 3.14, 2026-11-29, and $12.50.
Where simple tokenisers break
No short regex handles every language or text format correctly. Common difficult cases include:
- URLs, email addresses, and file paths, where punctuation is meaningful.
- Hyphenated words such as
state-of-the-art, which may be one token or several. - Apostrophes in names such as
O'Neill. - Emoji and other Unicode symbols.
- Abbreviations such as
Dr.andU.S.A. - Languages that do not consistently separate words with spaces.
- Code, markup, and product identifiers such as
C++,snake_case, andBERT-base.
These cases require a policy based on the task. A sentiment system may keep emoji as tokens. A web search system may preserve URLs. A programming-language tool needs rules for operators and identifiers.
Choosing a starting point
Use whitespace splitting when the text is controlled and a rough word sequence is enough. Use a regular expression when you need explicit rules for punctuation, contractions, or numbers. For production NLP, test the tokeniser against representative examples rather than assuming that a short pattern is universally correct.
Exercise
What tokens does the pattern r"\w+(?:'\w+)?|[^\w\s]" produce for the text "Cats, dogs!"?
Show answer
It produces ["Cats", ",", "dogs", "!"]. The words are matched by the first alternative, and the comma and exclamation mark are matched by the second.