Tokenization with spaCy
How spaCy splits text into tokens, what its tokenizer changes and preserves, how to customize it, and when its output suits your workflow.
Tokenization is the first step in almost every spaCy pipeline. Raw text becomes a sequence of tokens: words, punctuation marks, symbols and similar units. This review covers what the spaCy tokenizer does to your text, what it leaves untouched, where its default behavior helps or gets in the way, and how to judge whether its output fits what you plan to do with it.
Is spaCy tokenization suitable for your use?
Bounded recommendation: spaCy's tokenizer suits workflows that need linguistically sensible word boundaries and still need to map every token back to its exact place in the original text. Examples include feeding later pipeline components, extracting spans, highlighting matches, and annotating documents. Its main benefit is that it is non-destructive. Each token keeps its original characters and its trailing whitespace, so the source text can be rebuilt exactly.
The key tradeoff is that its boundaries are rule-based and language-specific. They reflect conventions such as splitting English contractions, and those conventions may not match your domain's idea of a 'word'. Product codes, chemical names, hashtags, file paths and informal spellings may need custom rules before the output is useful.
Plain text, or a simpler split, is often the better choice in these cases:
- You only need to display, store or share the text. Tokenization adds nothing there, and the original string is what readers and other tools expect.
- You need a fixed, easily reproduced split such as whitespace separation for a quick count, and linguistic boundaries would add complexity without changing the result.
- Your downstream model expects subword tokens from its own tokenizer, as many transformer models do. spaCy's word-level tokens are then an intermediate layer, not the final input.
- You are working in a language whose spaCy support relies on an external word segmenter you have not installed or evaluated.
What does the spaCy tokenizer actually change?
Terms such as 'reverse', 'mirror' and 'font' do not apply here. spaCy tokenization does not reorder characters, substitute look-alike Unicode glyphs or change how text is displayed. It segments the text. The characters stay as they were, and what changes is the structure built on top of them: a Doc object holding a sequence of Token objects.
The documented procedure for English and many other languages works in two stages:
- First, the text is split on whitespace characters.
- Then each substring is checked against special-case rules (tokenizer exceptions), such as contractions and abbreviations.
- If no special case applies, the tokenizer splits off prefixes such as opening quotes and brackets, and suffixes such as commas, periods, closing brackets and closing quotes. It also checks patterns that should be kept whole, such as URLs.
- Remaining substrings are split on infixes, such as hyphens between letters, where the language rules call for it.
The spaCy documentation illustrates this with the sentence "Let's go to N.Y.!". The contraction is split, the abbreviation is kept whole by an exception, and the final exclamation mark is split off as a suffix. The snippet below shows that documented result and the round-trip property. The output comments reflect the documented behavior of the default English rules; they were not produced by a test run for this article.
import spacy
nlp = spacy.blank("en") # tokenizer only, no trained components
text = "Let's go to N.Y.!"
doc = nlp(text)
print([token.text for token in doc])
# ['Let', "'s", 'go', 'to', 'N.Y.', '!']
print(doc.text == text)
# True: the original string is reconstructed exactly
Three properties make this non-destructive in practice. Each token's text attribute holds its characters unchanged. Its whitespace attribute records whether a space followed it in the source. Its idx attribute gives its character offset in the original string. Normalized forms such as the lowercase form, the norm and, when a lemmatizer is present, the lemma are stored as separate attributes. They never replace the original characters.
Some behaviors surprise people who expect a simple split:
- Runs of extra whitespace beyond a single space can appear as whitespace tokens of their own, which affects token counts.
- Tokenization does not split text into sentences. Sentence boundaries come from other components, such as a parser or a rule-based sentencizer.
- Tokens such as "'s" or "n't" are tokens of their own, so a word count based on tokens differs from a count of whitespace-separated words.
- For some languages, notably Chinese and Japanese, word segmentation depends on external libraries, so behavior depends on which segmenter is configured.
Combining marks and multi-code-point emoji: the brief's evidence check asks for these to be considered. The tokenizer works on Python strings, which are sequences of code points, and its prefix, suffix and infix rules are regular expressions. Splitting by default happens at whitespace and at punctuation-like characters, not between arbitrary code points, so a letter followed by a combining accent within a word would normally stay in one token. No documentation or test result was supplied here confirming how emoji sequences joined with zero-width joiners, skin-tone modifiers or flag pairs are handled in every case. If such characters matter to your data, test representative samples with the tokenizer's explain method before relying on the output.
Adjusting tokenization for your domain
When the default boundaries are wrong for your text, spaCy offers several documented levers. The lightest is a special case, which fixes how one exact string is split:
from spacy.symbols import ORTH
nlp.tokenizer.add_special_case("gimme", [{ORTH: "gim"}, {ORTH: "me"}])
print([token.text for token in nlp("gimme that")])
# ['gim', 'me', 'that']
- Special cases: exact-string rules, as above. The ORTH values must join back to the original string, which keeps the process non-destructive.
- Prefix, suffix and infix patterns: replace or extend the regular expressions the tokenizer uses for punctuation splitting.
- Token and URL matching patterns: keep strings that match a pattern together as single tokens.
- The retokenizer: merge or split tokens after tokenization, for example to join a multi-word name into one token.
- A fully custom tokenizer: replace the tokenizer with your own callable that returns a Doc, when the rule system does not fit at all.
- The explain method: shows which rule produced each token, which is the most direct way to debug an unexpected split.
Will the result remain usable after copying or sharing?
Tokenization output is a data structure, not a display format, so the usual concerns for styled or transformed text play out differently. When you export tokens, how usable they stay depends on how you serialize them:
- Copying the original text: unaffected. The Doc's text is the input string, character for character.
- Exporting a token list, such as a JSON array of strings: whitespace information and offsets are lost unless you include them. Rebuilding the original from tokens joined with single spaces will be wrong wherever no space existed, as with "Let" and "'s".
- Exporting with offsets: storing each token's start offset and length, or using spaCy's binary serialization, preserves the mapping back to the source. That mapping is what span highlighting and annotation tools usually need.
- Sharing between environments: retokenizing the same text later gives the same tokens only if the language, the spaCy version and any custom rules match. Record your configuration alongside exported tokens.
Reading order and assistive technology: tokenization does not change character order or visual presentation, so text you display from the original string reads the same to screen readers as untokenized text. Problems arise only if you present the token sequence itself to readers, for instance as space-separated tokens. Spacing then becomes misleading, and split contractions may be read oddly. For any reader-facing output, show the original text and keep tokens as a behind-the-scenes layer. No scoped test with a specific screen reader or destination application was supplied, so these points follow from how the data is structured, not from observed results.
Search and editing: if you index tokens for search, queries must be tokenized the same way, or terms such as contractions and hyphenated words may not match. If users edit the source text, the earlier tokens and offsets become stale, and the edited text must be tokenized again.
Evidence gaps
This review relies on spaCy's documented tokenizer design and general principles. No benchmark figures, version-specific test runs or measured comparisons with other tokenizers were supplied. Speed, accuracy on your domain, and handling of unusual Unicode sequences should therefore be checked on your own sample data before you commit to a workflow.