Implementing Text Tokenization for NLP: What It Changes and When It Fits
A practical review of text tokenization in NLP code: what splitting changes, Unicode pitfalls, offsets, normalization tradeoffs, and when plain text is better.
Tokenization splits a string into units, such as words, punctuation marks, subwords or characters, so that later code can count, index, compare or feed them to a model. It is a text transformation, and like any transformation it can preserve or distort what the original said. This review explains what tokenization changes, where common approaches in code lose information, and how to decide whether a given tokenizer is good enough for your purpose.
Is tokenization suitable for your intended use?
Tokenization is the right tool when a machine needs discrete units. Typical cases include word counts, search indexing, keyword extraction, classification features, and input to a language model. Its main benefit is that text becomes countable and comparable. The decisive tradeoff is that every tokenizer makes boundary decisions. Contractions, hyphenated words, accented characters, emoji and languages written without spaces can be split in ways that change what a unit means.
If the tokenized output will be shown to people, copied, quoted or edited, keep the original text and treat tokens as an internal working layer. Plain text is preferable whenever the result is meant to be read rather than processed.
- Good fit: counting, indexing, matching, feature extraction and model input, provided the original string is kept alongside the tokens.
- Good fit with care: multilingual or user-generated text, where normalization and grapheme handling matter.
- Poor fit: any output intended for human reading, quoting or editing. Use the original text for that.
- Model-specific case: transformer and other subword-based models need the tokenizer that matches the model's vocabulary. A generic word splitter is not a substitute.
What tokenization actually changes
A pure tokenizer does not alter the stored characters. It only decides where one unit ends and the next begins. In practice, many pipelines also change the characters themselves, through Unicode normalization, case folding, or discarding punctuation and whitespace. Keep these two kinds of change separate when you evaluate a workflow. Boundary decisions can be undone if you record positions. Character changes and discarded material cannot be undone unless the original is kept.
Tokenization is also unrelated to visual presentation. It operates on the logical order of characters as stored, not on how a font, a stylesheet or bidirectional display renders them. Right-to-left text is tokenized in its stored logical order, and that is the correct behavior. Styled lookalike characters, such as mathematical alphanumeric symbols used as decorative fonts, are different code points from ordinary letters. A tokenizer treats them as different text unless a compatibility normalization step maps them back.
The simplest approaches in Python show how much the boundary rule matters. Splitting on whitespace keeps contractions intact but leaves punctuation attached. A basic word-character regex removes punctuation but breaks contractions apart.
import re
text = "The café isn't open yet."
print(text.split())
# ['The', 'café', "isn't", 'open', 'yet.']
print(re.findall(r"\w+", text))
# ['The', 'café', 'isn', 't', 'open', 'yet']
Neither result is wrong in the abstract. The question is whether units like "yet." or "isn" and "t" serve your task. A slightly richer pattern keeps contractions together, accepts both straight and curly apostrophes, and emits punctuation as separate tokens. Recording start and end offsets makes each boundary decision traceable back to the source.
import re
TOKEN = re.compile(r"\w+(?:['’]\w+)*|[^\w\s]")
def tokenize(text):
return [(m.group(), m.start(), m.end()) for m in TOKEN.finditer(text)]
for token, start, end in tokenize("The café isn't open yet."):
print(token, start, end)
# The 0 3
# café 4 8
# isn't 9 14
# open 15 19
# yet 20 23
# . 23 24
These offsets assume "é" is stored as a single precomposed character. If it is stored as "e" plus a combining accent, every later offset shifts by one. That is one reason normalization should happen before tokenization, not after.
| Approach | What it decides | Main strength | Main limitation |
| Whitespace split | Boundaries only at spaces, tabs and newlines | Simple, never splits inside a word | Punctuation stays attached; fails for languages written without spaces |
| Word-character regex | Runs of letters, digits and underscore | Removes punctuation cleanly | Breaks contractions; can drop combining marks; ignores emoji |
| Custom regex with offsets | Rules you define, with positions recorded | Traceable and reversible to the source | Rules must be maintained for every script and edge case you handle |
| Dictionary or statistical segmenter | Word boundaries inferred from data | Handles scripts without spaces | Results depend on the segmenter and its data |
| Subword tokenizer tied to a model | Units from the model's learned vocabulary | Required for that model; covers rare words by splitting them into pieces | Pieces are not words; output is meaningful only for the matching model |
Unicode details that change results
Python's documentation defines the regex class \w, for str patterns, as alphanumeric characters as defined by str.isalnum() plus the underscore. Combining marks are not alphanumeric under that definition. A decomposed accented letter can therefore lose its accent during tokenization. Applying NFC normalization first composes the base letter and the mark into one character where a precomposed form exists.
import re
import unicodedata
decomposed = "cafe\u0301" # 'e' followed by a combining acute accent
print(re.findall(r"\w+", decomposed))
# ['cafe'] (the accent is not a word character and is dropped)
composed = unicodedata.normalize("NFC", decomposed)
print(re.findall(r"\w+", composed))
# ['café']
- NFC changes how characters are encoded but keeps their visible identity. It is usually a safe default before tokenizing.
- NFKC goes further and folds compatibility characters, such as ligatures, full-width forms and many styled lookalike letters, into ordinary ones. This helps matching but alters the stored text. Use it for indexing, not for text you will show back to people.
- Emoji built from several code points, such as sequences joined with zero-width joiners or carrying skin-tone modifiers, can be split into fragments by any rule that works one code point at a time. Python's standard library does not segment grapheme clusters. The third-party regex module supports \X for extended grapheme clusters, which keeps such sequences together.
- Languages such as Chinese, Japanese and Thai do not separate words with spaces. Whitespace and word-character rules cannot find word boundaries in them, so a dedicated segmenter is needed.
Will the result remain readable and usable after copying or sharing?
Token lists are not readable text. Joining tokens with spaces does not reproduce the original. The example above would come back as "The café isn't open yet .", with a stray space before the period, and any discarded punctuation, line breaks or casing would be gone for good. If people need to read, copy or quote the material, give them the original string. When you need to highlight tokens in context, slice the original text using stored offsets instead of rebuilding it from tokens.
Accessibility follows from the same point. Assistive technology reads the text it is given. Fragmented output such as separated contraction pieces or isolated punctuation is unlikely to read naturally. No scoped test with a specific screen reader was available for this review, so how a particular one announces tokenized output is unverified. The safe practice is to keep tokens out of user-facing content entirely.
Search and editing are where tokenization has the most practical effect. A search index only matches what its tokenizer produced. If documents and queries are tokenized or normalized differently, for example NFKC on one side and none on the other, or contractions split in one place and kept whole in another, matches will be missed. Use the same pipeline for both. Edits should be applied to the original text, and tokens should be regenerated afterward rather than edited directly.
When plain text is the better choice
Keep plain, untokenized text whenever the output is for human reading, legal or quoted material, editing, or anything that must round-trip exactly. Tokenize a copy for machine use. Record offsets if you need to map results back, and document which normalization was applied so the transformation can be audited.
Gaps in the available evidence
No benchmarks, accuracy figures, library version comparisons or destination-specific tests were supplied for this review. The code behavior described above follows from documented Python and Unicode definitions. It is not a measured comparison of tokenizers. How a specific library, model tokenizer, search engine or assistive technology handles your text should be confirmed with a small test on representative input, including accented characters, contractions, multi-code-point emoji and any scripts you expect to process.