Splitting Text: Sentences, Words and Regex Tokenizers
Every classical NLP model, from a bag of words to an n-gram language model, works on tokens: the units it counts. Before you can count anything you must decide where one unit ends and the next begins, and text does not make that easy. Full stops end sentences and abbreviations, apostrophes join "don't" and quote words, hyphens build "e-bike" and break lines, and some languages put no spaces between words at all. The choice shapes the vocabulary: split too little and every punctuation variant is a new word ("lock", "lock,", "lock."), split too much and "U.S." becomes the meaningless pair "U" and "S".
This lesson builds a rule-based sentence splitter and regex word tokenizers, compares them with NLTK's tokenizers, and then measures the problem that every word-level tokenizer runs into, however carefully it is written: the vocabulary never stops growing, so new text always contains words the model has never seen. That problem is what subword tokenizers solve.
Sentences: the full stop is ambiguous
Splitting into sentences matters for summarisation, for sentence-level classifiers, for chunking documents before retrieval and for any model with a length limit. The obvious rule, "split after ., ! or ? followed by a space", fails on abbreviations, initials, decimal numbers and times. The example compares it with a rule-based splitter that knows a short abbreviation list and checks whether the next word starts with a capital letter or a digit.
import re
text = ("Dr. Lee rode 3.5 km to the U.S. office, e.g. via Main St. at 8 a.m. "
"She paid 4.50 euros. Was it worth it?! Yes... mostly. "
"Next ride: tomorrow.")
naive = [s for s in re.split(r"(?<=[.!?])\s+", text) if s]
print(len(naive), "naive sentences:")
for s in naive:
print(" |", s)
ABBREV = {"dr", "mr", "mrs", "st", "e.g", "i.e", "u.s", "a.m", "p.m", "etc", "vs"}
def split_sentences(text):
sents, start = [], 0
for m in re.finditer(r"[.!?]+(?=\s+|$)", text):
before = text[start:m.end()].split()[-1].rstrip(".!?").lower()
nxt = text[m.end():].lstrip()[:1]
if m.group() == "." and before in ABBREV and not (before in {"a.m", "p.m"} and nxt.isupper()):
continue # an abbreviation, not a sentence end
if nxt and not (nxt.isupper() or nxt.isdigit()):
continue # next word lower-case: probably mid-sentence
sents.append(text[start:m.end()].strip())
start = m.end()
if text[start:].strip():
sents.append(text[start:].strip())
return sents
better = split_sentences(text)
print(len(better), "rule-based sentences:")
for s in better:
print(" |", s)10 naive sentences:
| Dr.
| Lee rode 3.5 km to the U.S.
| office, e.g.
| via Main St.
| at 8 a.m.
| She paid 4.50 euros.
| Was it worth it?!
| Yes...
| mostly.
| Next ride: tomorrow.
5 rule-based sentences:
| Dr. Lee rode 3.5 km to the U.S. office, e.g. via Main St. at 8 a.m.
| She paid 4.50 euros.
| Was it worth it?!
| Yes... mostly.
| Next ride: tomorrow.
The naive rule produces 10 "sentences", half of them broken at "Dr.", "U.S.", "e.g.", "St." and "a.m.". The rule-based splitter gets the 5 real sentences. Its two rules carry the weight: a full stop after a known abbreviation is not a boundary, and a boundary must be followed by an upper-case letter or a digit ("Yes... mostly." stays one sentence because "mostly" is lower case). The decimal "3.5" never matched in the first place, because the pattern requires white space after the punctuation.
Rules like these are brittle in both directions. "a.m." is in the list, so the splitter needs a special case to end a sentence after "8 a.m." when a capitalised word follows; an abbreviation that really does end a sentence ("He moved to the U.S. Then...") is ambiguous even for people; and a lower-case product name at the start of a sentence ("iPhone sales rose") defeats the capital-letter rule. NLTK's sent_tokenize uses the Punkt model, which learns abbreviations, collocations and typical sentence starters from raw text without labels. It needs the punkt_tab data package, which the browser cannot download, so it is shown here without running:
import nltk
nltk.download("punkt_tab") # needs the network once
from nltk.tokenize import sent_tokenize, word_tokenize
sent_tokenize("Dr. Lee rode to the U.S. office. She paid 4.50 euros.")
# ['Dr. Lee rode to the U.S. office.', 'She paid 4.50 euros.']
word_tokenize("Don't stop.") # ['Do', "n't", 'stop', '.']For noisy text (chat messages without punctuation, transcribed speech) no punctuation rule works; there, sentence boundaries are predicted by a trained tagger, or the text is simply cut into fixed-length windows.
Words: regex tokenizers from scratch
A word tokenizer is usually a regular expression applied with re.findall. The simplest, \w+, keeps runs of letters, digits and underscores and drops everything else. A better one lists the token shapes you care about, most specific first, because the regex engine tries the alternatives left to right at each position:
- abbreviations made of capital letters and dots (
U.S.); - numbers and prices, with an optional currency sign and decimal part;
- words that may contain inner hyphens or apostrophes (
e-bike,don't); - any other single symbol, so punctuation becomes its own token instead of disappearing.
NLTK ships three tokenizers that need no data downloads: TreebankWordTokenizer (the conventions of the Penn Treebank, used by many parsers and older datasets), wordpunct_tokenize (alphanumeric runs and punctuation runs) and RegexpTokenizer (your own pattern).
import re
from nltk.tokenize import TreebankWordTokenizer, RegexpTokenizer, wordpunct_tokenize
s = "Don't re-scan the QR-code; it's e-bike #42 (U.S. model), costs $3.50/hour."
simple = re.findall(r"\w+", s)
pattern = r"""(?x) # verbose regex
(?:[A-Z]\.)+ # abbreviations: U.S.
| \$?\d+(?:\.\d+)? # numbers and prices: $3.50, 42
| \w+(?:[-']\w+)* # words with inner hyphens or apostrophes
| [^\w\s] # any other single symbol
"""
mine = re.findall(pattern, s)
print("\\w+ ", len(simple), simple)
print("mine ", len(mine), mine)
print("Treebank ", TreebankWordTokenizer().tokenize(s))
print("wordpunct ", wordpunct_tokenize(s))
print("Regexp ", RegexpTokenizer(r"[A-Za-z]+").tokenize(s))\w+ 19 ['Don', 't', 're', 'scan', 'the', 'QR', 'code', 'it', 's', 'e', 'bike', '42', 'U', 'S', 'model', 'costs', '3', '50', 'hour']
mine 19 ["Don't", 're-scan', 'the', 'QR-code', ';', "it's", 'e-bike', '#', '42', '(', 'U.S.', 'model', ')', ',', 'costs', '$3.50', '/', 'hour', '.']
Treebank ['Do', "n't", 're-scan', 'the', 'QR-code', ';', 'it', "'s", 'e-bike', '#', '42', '(', 'U.S.', 'model', ')', ',', 'costs', '