TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Splitting Text: Sentences, Words and Regex Tokenizers

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.

python · try it yourself
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:

python
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:

  1. abbreviations made of capital letters and dots (U.S.);
  2. numbers and prices, with an optional currency sign and decimal part;
  3. words that may contain inner hyphens or apostrophes (e-bike, don't);
  4. 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).

python · try it yourself
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', '
  

, '3.50/hour', '.']
wordpunct  ['Don', "'", 't', 're', '-', 'scan', 'the', 'QR', '-', 'code', ';', 'it', "'", 's', 'e', '-', 'bike', '#', '42', '(', 'U', '.', 'S', '.', 'model', '),', 'costs', '
  

, '3', '.', '50', '/', 'hour', '.']
Regexp     ['Don', 't', 're', 'scan', 'the', 'QR', 'code', 'it', 's', 'e', 'bike', 'U', 'S', 'model', 'costs', 'hour']

The outputs differ on every hard case:

Input \w+ my pattern Treebank wordpunct
Don't Don, t Don't Do, n't Don, ', t
it's it, s it's it, 's it, ', s
e-bike e, bike e-bike e-bike e, -, bike
U.S. U, S U.S. U.S. U, ., S, .
price per hour 3, 50, hour $3.50, /, hour $, 3.50/hour $, 3, ., 50, /, hour

Treebank splits contractions into two linguistic units, Do + n't and it + 's, which is what a parser wants: "n't" is the negation, and keeping it as a token lets a sentiment model learn one weight for negation instead of separate weights for "don't", "isn't", "wasn't". Keeping Don't whole (my pattern) is simpler and fine for retrieval. \w+ produces the worst of both: a lone t and s. Hyphens are a design choice: e-bike as one token keeps the meaning, but then "e-bike", "ebike" and "e bike" are three different spellings of one word, so a search system may want to index both the whole form and its parts. And no tokenizer handled the price well: Treebank glued 3.50/hour together because it does not split on /. Write tests with your own data's difficult strings (prices, dates, product codes, URLs, emoji) before choosing.

Note: Chinese, Japanese and Thai are written without spaces between words, so white-space and regex tokenizers do not apply. Word segmentation there is a learned task (dictionary-based maximum matching was the classical baseline, statistical and neural segmenters replaced it), and many systems skip it entirely and work on characters or subwords. Agglutinative languages such as Finnish and Turkish have the opposite issue: one "word" can carry what English spreads over a whole phrase, so word-level vocabularies explode.

The vocabulary never stops growing

Word frequencies in natural language follow Zipf's law: the rr-th most frequent word has a frequency roughly proportional to 1/rs1/r^s with ss close to 1. A few words ("the", "of") are extremely common and most words are rare; in a typical corpus about half of the distinct words occur only once (in the synthetic corpus below, 11,800 of 21,516, or 55%). The consequence for vocabulary size is Heaps' law: the number of distinct words VV in a text of nn tokens grows like a power of nn,

V(n)≈Knβ,0<β<1,V(n) \approx K n^{\beta}, \qquad 0 < \beta < 1,

so it keeps growing, only more slowly than the text. Real English corpora give β\beta somewhere around 0.4 to 0.6 (often close to 0.5) depending on the corpus and the tokenizer. Fitting KK and β\beta is a straight line in log-log space: log⁡V=log⁡K+βlog⁡n\log V = \log K + \beta \log n.

The practical cost shows up on held-out text: a word-level model knows only the words of its training data, and every other word becomes an out-of-vocabulary (OOV) token, usually mapped to a single <unk>. The example samples 220,000 tokens from a Zipf distribution with s=1.1s = 1.1 over 50,000 word types (a synthetic stand-in for a real corpus, so the numbers are exact and reproducible), builds vocabularies from the first nn tokens and measures the OOV rate on the last 20,000.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
V_true, s = 50_000, 1.1                       # word types and Zipf exponent
p = 1.0 / np.arange(1, V_true + 1) ** s
p /= p.sum()
tokens = rng.choice(V_true, size=220_000, p=p)
train, held = tokens[:200_000], tokens[200_000:]

ns = np.array([1_000, 3_000, 10_000, 30_000, 100_000, 200_000])
V = np.array([len(np.unique(train[:n])) for n in ns])
beta, logK = np.polyfit(np.log(ns), np.log(V), 1)
print("tokens  types  predicted  OOV on held-out")
for n, v in zip(ns, V):
    seen = np.zeros(V_true, dtype=bool)
    seen[train[:n]] = True
    oov = 1 - seen[held].mean()
    print(f"{n:7d} {v:6d} {np.exp(logK) * n ** beta:9.0f}  {oov:6.1%}")
print(f"Heaps fit: V(n) = {np.exp(logK):.1f} * n^{beta:.3f}")

counts = np.bincount(train, minlength=V_true)
for k in (1, 2, 5):
    keep = counts >= k
    print(f"keep words seen >= {k}: vocab {keep.sum():6d}, held-out tokens mapped to <unk> {1 - keep[held].mean():.1%}")
tokens  types  predicted  OOV on held-out
   1000    483       510   37.2%
   3000   1122      1127   30.1%
  10000   2842      2686   22.0%
  30000   6352      5931   15.5%
 100000  14333     14135    9.1%
 200000  21516     23303    6.2%
Heaps fit: V(n) = 3.5 * n^0.721
keep words seen >= 1: vocab  21516, held-out tokens mapped to <unk> 6.2%
keep words seen >= 2: vocab   9716, held-out tokens mapped to <unk> 10.4%
keep words seen >= 5: vocab   3047, held-out tokens mapped to <unk> 16.4%

The fitted exponent is β=0.721\beta = 0.721: multiplying the text by 10 multiplies the vocabulary by about 100.721≈5.310^{0.721} \approx 5.3. (With an unlimited number of word types the exponent would tend to 1/s≈0.911/s \approx 0.91; the finite 50,000 types flatten the curve.) The OOV rate falls as the training text grows, from 37.2% with 1,000 tokens to 6.2% with 200,000, but slowly: even then, one held-out token in sixteen is unknown. The usual fix for a word-level vocabulary, dropping rare words, makes it worse. Keeping only words seen at least 5 times shrinks the vocabulary from 21,516 to 3,047 entries, a seventh of the size, but raises the share of held-out tokens mapped to <unk> from 6.2% to 16.4%.

Those unknown tokens are exactly the informative ones: names, product codes, misspellings, new slang, technical terms. A model that sees "my bike <unk> is <unk>" cannot tell a flat tyre from a stolen bike. Character-level models have no OOV problem but produce very long sequences. Subword tokenizers (BPE, WordPiece, Unigram) take the middle path: frequent words stay whole and rare words are split into known pieces, so the vocabulary has a fixed size and there is no <unk> at all. They are the subject of the Tokenizers section, starting with Why Subword Tokenizers; Tokens gives the short version.

Pitfalls

  • Different tokenizers at training and serving time. A model trained on Treebank tokens and served with str.split() sees "lock." where it learned "lock" and "."; keep the tokenizer in the same pipeline object as the model.
  • Splitting sentences before normalising. Zero-width or no-break spaces hide boundaries from a splitter that looks for ordinary spaces; normalise first (Text Normalisation).
  • Dropping punctuation by default. Question marks, exclamation marks and emoticons are features for intent and sentiment.
  • Measuring the vocabulary on all data. Build the vocabulary from the training split only; otherwise the OOV rate you measure on the test split is zero by construction and the model looks better than it is.
  • Assuming one tokenizer fits all languages. White-space rules fail for Chinese, Japanese and Thai and degrade for agglutinative languages.

Practice

  1. Add one rule to the sentence splitter so that "He moved to the U.S. Then he bought a bike." is split into two sentences. What new error might the rule introduce?
  2. Write a regex alternative that keeps times like 8:30 and dates like 2026-11-22 as single tokens. Where in the pattern must it go?
  3. Using the fitted Heaps' law V(n)=3.5 n0.721V(n) = 3.5\, n^{0.721}, roughly how many distinct words do you expect in 2,000,000 tokens?
  4. Why does the OOV rate with min-count 2 (10.4%) exceed the one with min-count 1 (6.2%), although the training text is the same?
  5. A sentiment model uses \w+ tokens. What happens to "isn't" and "wasn't", and why is that bad?
Answers
  1. Treat an abbreviation from a small "can end a sentence" set (u.s, etc) as a boundary when the next word is capitalised and is a common sentence starter ("Then", "The", "She"). New error: "the U.S. Navy" or "the U.S. President" would be split if a capitalised name follows; learning such cases from data is what Punkt does.
  2. \d{4}-\d{2}-\d{2} and \d{1,2}:\d{2}, placed before the general number alternative: the engine takes the first alternative that matches at a position, and \d+(?:\.\d+)? would otherwise match just 2026 or 8.
  3. 3.5×(2×106)0.721≈3.5×35,000≈120,0003.5 \times (2 \times 10^6)^{0.721} \approx 3.5 \times 35{,}000 \approx 120{,}000, but the synthetic data has only 50,000 types, so the real count would stay below 50,000: power laws fitted on one range break when a limit is reached.
  4. Words seen exactly once in training are removed from the vocabulary, but many of them occur again in held-out text, and every such occurrence now counts as <unk>. Removing words never lowers the OOV rate.
  5. They become isn, t and wasn, t: the negation is a lone t shared with other contractions ("it's" gives s, "don't" gives t), and "isn" is a meaningless fragment. A Treebank-style split (is, n't) keeps the negation as one clear token.

Test yourself

Why does the naive rule 'split after a full stop followed by a space' produce 10 sentences instead of 5?

  1. It splits after abbreviations such as Dr., U.S. and e.g.
  2. It splits inside the decimal number 3.5
  3. It ignores question marks
  4. It splits at every comma

How does TreebankWordTokenizer split Don't?

  1. Don't
  2. Don, ', t
  3. Do, n't
  4. Don, t

Heaps' law V(n)≈KnβV(n) \approx K n^{\beta} with β=0.721\beta = 0.721. The training text grows 10 times. The vocabulary grows by about:

  1. 10 times
  2. 5.3 times
  3. 2 times
  4. It stops growing

In the experiment, keeping only words seen at least 5 times changed the held-out <unk> rate from 6.2% to:

  1. 3.1%
  2. 6.2%
  3. 10.4%
  4. 16.4%

What do subword tokenizers fix compared with word-level vocabularies?

  1. They remove the need for training data
  2. Rare and unseen words are split into known pieces, so there is no <unk> and the vocabulary has a fixed size
  3. They make every token a whole word
  4. They only work for English