AI Wiki中文/EN

Tokenization: where does one unit end?

分词与词元化

Compare boundary policies, preserve byte and code-point offsets, and solve a weighted dictionary segmentation with dynamic programming.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Count the units before counting the words

Here is an invented input for a text-processing pipeline:

Mina's café—AI costs 3.50.\t研究生命 👩‍💻

In the program, \t is one tab. Splitting on whitespace leaves café—AI and 3.50. intact. A punctuation-aware rule can separate the dash and full stop, but our chosen rule also splits the decimal into 3, ., 50. Chinese characters do not need intervening spaces to form several words. The displayed programmer emoji contains three code points: a woman, a zero-width joiner and a laptop.

A token is a unit chosen by a procedure. It may be a word, punctuation mark, subword, code point or byte. Choosing the procedure defines the units that the next model will see. NLTK introduces tokenization through this boundary decision and the simple whitespace baseline; the program here compares explicit original policies rather than assuming one policy fits every language. NLTK, tokenization introduction

This topic starts with the original string. Text normalization changes that string under a separate policy; stemming and lemmatization change or annotate tokens afterward. Neither operation should be hidden inside an offset calculation.

Both dictionary paths reconstruct the same string, yet their costs and exact-span F1 differ. The lower table converts the same token span between code points and UTF-8 bytes.
Costs use a fixed0–5 scale; gold is explicitly研究|生命. Offset pairs are half-open. These are supplied examples, not corpus accuracy.

Boundaries need units, and a path needs an objective

A token trace that can be checked

Let s contain n Unicode scalar values, indexed from zero. Represent the i-th token by the half-open code-point interval [a_i,b_i). Intervals are nonempty, ordered and nonoverlapping; gaps are permitted:

0≤a1<b1≤a2<b2≤⋯≤ak<bk≤n.0\le a_1<b_1\le a_2<b_2\le\cdots\le a_k<b_k\le n.

Half-open means that a is included and b is excluded. The token text is s[a:b]. Keeping only token strings may lose spaces, tabs and newlines. Our trace retains each preceding gap g_i and the final tail g_tail, so concatenation recovers the input:

s=g1t1g2t2⋯gktkgtail.s=g_1t_1g_2t_2\cdots g_kt_kg_{\mathrm{tail}}.

The code actually joins these fields when testing reconstruction; comparing a stored raw field to itself would not test anything. Reconstruction can pass even when boundaries are unsuitable for the task. Splitting every code point, including spaces, also round-trips.

UTF-8 byte offsets use a different coordinate system. Define a prefix byte length B_j, then translate a code-point interval using its two endpoints:

Bj=∑r=0j−1∣UTF8⁡(sr)∣,[a,b)↦[Ba,Bb).B_j=\sum_{r=0}^{j-1}|\operatorname{UTF8}(s_r)|,\qquad [a,b)\mapsto[B_a,B_b).

Café has four code points and five UTF-8 bytes. In Café 研究, the Chinese token occupies code points [5,7) but bytes [6,12). An annotation consumer expecting bytes will not correctly interpret the numbers 5 and 7. Likewise, each byte is not necessarily valid UTF-8 by itself: the final two bytes of Café, 195 and 169, decode together as é, but each alone fails strict decoding. A byte tokenizer needs a decoding contract for combined output, not an assumption that each piece is a printable character.

Three transparent policies

PolicyRuleA useful counterexample
Code pointOne token per Python string elementThe emoji above becomes three units, not one displayed symbol
WhitespaceMatch each non-whitespace runPunctuation attached to a word stays attached
Chosen regexWord-character runs with internal apostrophes, otherwise one nonspace punctuation/symbol3.50 becomes three tokens; a Chinese run stays together

For Unicode strings, Python’s \w includes Unicode alphanumeric characters and underscore. It does not mean “English word” or “complete linguistic word.” CPython v3.12.4, re With our pattern, a decomposed acute accent becomes a separate token, while the precomposed é can stay in a word run. Record whether normalization preceded tokenization. This is not a Unicode grapheme-cluster algorithm or a claim of UAX29 conformance.

Chinese segmentation as a weighted path

For an original toy example, use the string 研究生命 and the supplied dictionary:

EntryCost
研究1
研究生0.5
生命1
命4

Place nodes at code-point boundaries 0 through n. An edge (i,j) exists when s[i:j] is a dictionary entry; its cost is the supplied number. At every position, allow a one-code-point fallback of cost10 unless that single character already has a dictionary entry, in which case its dictionary cost is used. Edges always move forward, so the graph is acyclic and every position is reachable.

Longest matching greedily selects 研究生 | 命, costing4.5. The alternative 研究 | 生命 costs2. A long first word, even one with a small local cost, does not establish the best complete path. The global objective is:

π^=arg⁡min⁡π:0⇝n∑(i,j)∈πc(i,j).\hat\pi=\arg\min_{\pi:0\leadsto n}\sum_{(i,j)\in\pi}c(i,j).

Let D(j) be the minimum cost of covering the first j code points. The last edge into j must start at some earlier i, giving:

D(0)=0,D(j)=min⁡(i,j)∈E{D(i)+c(i,j)}.D(0)=0,\qquad D(j)=\min_{(i,j)\in E}\{D(i)+c(i,j)\}.

Process boundaries in increasing order and store the predecessor of each improved value. Induction proves the recurrence: an optimal path ending at j consists of an optimal prefix ending at its predecessor plus the last edge; replacing a more expensive prefix would improve the whole path. Backtracking predecessors recovers the segmentation. Our loop keeps the first path encountered on equal totals; this is a deterministic tie rule, not a preference inferred from language.

For longest dictionary word length L, there are O(nL) candidate substring positions. In this Python implementation, creating and hashing a length-l substring costs O(l), so the worst-case scanning time is O(nL²), under average constant-time dictionary lookup after hashing. The DP arrays need O(n) space; transient substring candidates can hold O(L²) characters. Output and input dictionary storage are additional. A trie could share prefix scans, but that is not what this code implements. The demonstration caps text length at256, dictionary entries at256 and word length at64.

Measure the annotation decision separately

Suppose the declared gold segmentation is 研究 | 生命. Compare exact token spans, not just the number of tokens or the reconstructed string. Let P and G be the predicted and gold span sets on the same raw string:

precision⁡=∣P∩G∣∣P∣,recall⁡=∣P∩G∣∣G∣,F1=2∣P∩G∣∣P∣+∣G∣.\operatorname{precision}=\frac{|P\cap G|}{|P|},\quad \operatorname{recall}=\frac{|P\cap G|}{|G|},\quad F_1=\frac{2|P\cap G|}{|P|+|G|}.

Here longest matching scores0 and DP scores1. A shared sentence endpoint is not a shared full token span. Zero denominators are defined as zero in this teaching scorer. These numbers concern one supplied annotation, not real-corpus accuracy or semantic understanding. Changing the gold convention can change which result scores best.

Run the trace and the two competing paths

Save the following complete program as tokenization.py and run python3 tokenization.py; it uses only the standard library. Inputs must be strings without surrogate code points. It preserves case, normalization form, gaps and original text. The dictionary example rejects whitespace and non-finite costs, and raises an error on accumulated cost overflow instead of silently returning an infinite path.

"""Original token boundary and weighted dictionary segmentation experiment.

No normalization, pretrained tokenizer or universal linguistic-boundary claim.
All offsets name their unit; removed whitespace is retained as reconstruction
gaps. The dictionary model is a supplied finite weighted DAG, not a trained LM.
"""
import json
import math
import re


def scalar_text(text):
    if not isinstance(text,str) or any(0xD800<=ord(c)<=0xDFFF for c in text):
        raise ValueError('A Unicode string without surrogate code points is required')
    return text


def trace_spans(text,spans):
    text=scalar_text(text);spans=list(spans);prefix=[0]
    for character in text:prefix.append(prefix[-1]+len(character.encode('utf-8')))
    rows=[];previous=0
    for pair in spans:
        if not isinstance(pair,(tuple,list)) or len(pair)!=2:raise ValueError('Pairs of code-point offsets required')
        start,end=pair
        if type(start) is not int or type(end) is not int or not previous<=start<end<=len(text):
            raise ValueError('Sorted, nonoverlapping, nonempty in-range spans required')
        rows.append({'text':text[start:end],'codepoint_span':[start,end],
                     'utf8_span':[prefix[start],prefix[end]],'gap':text[previous:start]})
        previous=end
    return {'raw':text,'tokens':rows,'tail':text[previous:],'units':'half-open code-point and UTF-8 byte spans'}


def reconstruct(trace):
    return ''.join(row['gap']+row['text'] for row in trace['tokens'])+trace['tail']


def tokenize(text,policy):
    text=scalar_text(text)
    if policy=='codepoint':spans=[(i,i+1) for i in range(len(text))]
    elif policy=='whitespace':spans=[match.span() for match in re.finditer(r'\S+',text)]
    elif policy=='regex':
        # This chosen pattern groups word characters and internal apostrophes.
        # It does not implement grapheme clusters or language-specific words.
        spans=[match.span() for match in re.finditer(r"\w+(?:['’]\w+)*|[^\w\s]",text)]
    else:raise ValueError('Choose codepoint, whitespace or regex')
    return trace_spans(text,spans)


def checked_dictionary(text,lexicon,unknown_cost):
    scalar_text(text)
    if len(text)>256 or any(c.isspace() for c in text):raise ValueError('Dictionary example accepts at most256 code points without whitespace')
    if not isinstance(lexicon,dict) or not lexicon or len(lexicon)>256:raise ValueError('A nonempty dictionary of at most256 entries is required')
    for word,cost in lexicon.items():
        scalar_text(word)
        if not 1<=len(word)<=64 or any(c.isspace() for c in word):raise ValueError('Dictionary words must contain1–64 nonspace code points')
        if isinstance(cost,bool) or not isinstance(cost,(int,float)) or not math.isfinite(cost) or cost<0:raise ValueError('Finite nonnegative word costs required')
    if isinstance(unknown_cost,bool) or not isinstance(unknown_cost,(int,float)) or not math.isfinite(unknown_cost) or unknown_cost<=0:
        raise ValueError('A positive finite single-code-point fallback cost is required')
    return max(map(len,lexicon))


def edges(text,start,lexicon,unknown_cost,max_length):
    result=[]
    for end in range(min(len(text),start+max_length),start,-1):
        word=text[start:end]
        if word in lexicon:result.append((end,float(lexicon[word]),False))
    if text[start:start+1] not in lexicon:result.append((start+1,float(unknown_cost),True))
    return result


def segment(text,lexicon,unknown_cost=10.,method='optimal'):
    maximum=checked_dictionary(text,lexicon,unknown_cost)
    if method not in ['optimal','longest']:raise ValueError('Choose optimal or longest')
    n=len(text);costs=[math.inf]*(n+1);costs[0]=0.;parents=[None]*(n+1);examined=0
    if method=='optimal':
        for start in range(n):
            if not math.isfinite(costs[start]):continue
            for end,cost,unknown in edges(text,start,lexicon,unknown_cost,maximum):
                examined+=1;candidate=costs[start]+cost
                if not math.isfinite(candidate):raise ValueError('Path cost overflow')
                # Equal totals retain the first path reached by this traversal.
                if candidate<costs[end]:costs[end]=candidate;parents[end]=(start,unknown)
    else:
        start=0
        while start<n:
            candidates=edges(text,start,lexicon,unknown_cost,maximum);examined+=len(candidates)
            end,cost,unknown=candidates[0]
            total=costs[start]+cost
            if not math.isfinite(total):raise ValueError('Path cost overflow')
            costs[end]=total;parents[end]=(start,unknown);start=end
    spans=[];unknown_flags=[];end=n
    while end:
        start,unknown=parents[end];spans.append((start,end));unknown_flags.append(unknown);end=start
    spans.reverse();unknown_flags.reverse();trace=trace_spans(text,spans)
    for row,flag in zip(trace['tokens'],unknown_flags):row['fallback']=flag
    trace.update(method=method,total_cost=costs[n],candidate_edges_examined=examined,
                 fallback_count=sum(unknown_flags),cost_scope='Supplied additive costs, not estimated probabilities or human correctness.')
    return trace


def token_span_score(predicted,gold):
    # Both traces must name exactly the same surface string and coordinate unit.
    if predicted['raw']!=gold['raw']:raise ValueError('Cannot score spans on different strings')
    p={tuple(row['codepoint_span']) for row in predicted['tokens']};g={tuple(row['codepoint_span']) for row in gold['tokens']}
    correct=len(p&g);precision=correct/len(p) if p else 0.;recall=correct/len(g) if g else 0.
    f1=2*correct/(len(p)+len(g)) if p or g else 0.
    return {'predicted':len(p),'gold':len(g),'exact_spans':correct,'precision':precision,'recall':recall,'f1':f1,
            'empty_convention':'Zero denominators yield zero; this is a declared token-span score, not semantic quality.'}


def demo():
    text="Mina's café—AI costs 3.50.\t研究生命 👩\u200d💻"
    policies={name:tokenize(text,name) for name in ['codepoint','whitespace','regex']}
    lexicon={'研究':1.,'研究生':.5,'生命':1.,'命':4.}
    candidates={name:segment('研究生命',lexicon,method=name) for name in ['longest','optimal']}
    gold=trace_spans('研究生命',[(0,2),(2,4)])
    byte_text='Café';raw_bytes=byte_text.encode('utf-8');valid=[]
    for value in raw_bytes:
        try:bytes([value]).decode('utf-8');valid.append(True)
        except UnicodeDecodeError:valid.append(False)
    return {'text':text,'policy_traces':policies,'roundtrips':{k:reconstruct(v)==text for k,v in policies.items()},
            'dictionary':lexicon,'segmentations':candidates,
            'declared_gold_scores':{k:token_span_score(v,gold) for k,v in candidates.items()},
            'byte_units':{'text':byte_text,'bytes':list(raw_bytes),'codepoints':len(byte_text),'individually_valid_utf8':valid,
                          'joined_decodes':bytes(raw_bytes).decode('utf-8')==byte_text},
            'scope':'Original policies and finite weighted dictionary example. Gold is explicitly supplied. No grapheme/UAX29 conformance, universal tokenizer, learned probabilities or real-corpus benchmark.'}


if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2))

The output contains every token’s surface text, both offset units and gaps, followed by the two dictionary paths and their declared-gold scores. All three policy traces reconstruct the input. The accompanying checks independently enumerate cut patterns of short binary strings to compare the DP minimum, test offset values by hand, and exercise empty input, fallback, ties and invalid spans. These finite checks cover the stated program; they do not certify a universal tokenizer.

Choose the errors that matter to the application

A search index may want punctuation split; a financial extraction task may need decimal numbers intact. A span annotation task needs a stable relation to the original string. Our whitespace baseline is cheap to inspect but discovers no boundaries inside a Chinese run; our regex adds decisions without learning context. The weighted dictionary DP uses supplied additive costs. Calling them probabilities would require a separate normalized model and an account of how its parameters were estimated.

Learned word or subword methods can handle a different vocabulary tradeoff; their training text, unknown-token policy, encoding and decoding still need specification. This article does not implement BPE, SentencePiece, a morphological segmenter or grapheme boundaries. Pick an annotation policy and a held-out task evaluation before declaring one tokenizer better. Preserve original offsets when transforming text, and check round trips separately from boundary quality.

Try to break an apparently sensible boundary rule

  1. In Café 研究, what are the two offset intervals of 研究?

Answer: Code points [5,7); UTF-8 bytes [6,12). Café uses5 bytes and the following space uses1. Each Chinese character contributes3 bytes. The intervals identify the same surface token in different units.

  1. Raise the cost of 生命 from1 to4, keeping the rest of the dictionary unchanged. Which of the two displayed paths has lower total cost?

Answer: 研究 | 生命 now costs5; 研究生 | 命 remains4.5. The greedy path wins this comparison. DP follows the declared costs, so it is not hard-coded to the original gold split; the fallback paths here still cost more.

  1. A system drops whitespace, joins token strings, and claims success because its stored raw field equals the input. What check is missing?

Answer: Reconstruct from the actual retained tokens and gaps, then compare to the original. Equality of two raw-string copies says nothing about whether the token representation preserved tabs, repeated spaces or line breaks. Even a genuine round trip does not establish correct linguistic boundaries.

  1. A name recognizer was trained on NFC text but receives decomposed accents at deployment. Should one merely adjust the token-span scorer?

Answer: No. First align the declared normalization and tokenization policies, and preserve the mapping to raw-text annotations. Our regex can split the decomposed accent differently, changing model input before scoring begins. Only compare spans on the same surface string and coordinate system; report the policy and evaluate unseen examples.

Use library definitions without hiding policy choices

NLTK’s textbook provides the progression from simple string processing to tokenization. Python’s fixed-version documentation gives the precise \w semantics used here. The offset ledger, weighted dictionary example, independent enumeration and scoring convention are original teaching constructions; neither source reports their numerical results as a language benchmark. The next topic examines what happens when distinct tokens are intentionally given the same stem or lemma.

Make a prediction, then check

The longest first word costs0.5, followed by a word costing4; two shorter words cost1 each. Which cut minimizes the supplied total?

Choose one answer

Learning objectives

  • Separate a token, a code point and a UTF-8 byte.
  • Reconstruct raw text with token spans and retained gaps.
  • Derive and check minimum-cost dictionary segmentation.
  • Interpret exact-span F1 under an explicit annotation convention.

Prerequisites & connections

Explore related knowledge →

References

  1. NLTK Book: tokenization and normalization sections
    Steven Bird; Ewan Klein; Edward Loper · 2026
  2. CPython v3.12.4: Unicode word characters in regular expressions
    Python documentation contributors · 2024

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-08 · Codex single-AI-author technical check: pinned NLTK/Python boundary definitions, six paired equations, code-point/UTF8 offsets, actual gap reconstruction, weighted-DAG minimum recurrence and substring-copy complexity, declared-span F1, four explained exercises and computed SVGs. Independent short-string path enumeration; no universal segmentation or grapheme conformance. Production browser acceptance recorded separately.

  • Compared both languages: independent token/byte/code-point units, interval validity, gaps, complete input reconstruction, Unicode regex limitations, additive path objective and optimal-substructure proof, O(nL²) substring work, explicit gold and zero-denominator convention. Six equations and four explained exercises correspond.
  • Formal suite executes production MDX:15 independent prototype cases, original changed-cost exercise and6 publication checks. Includes exhaustive cut-pattern comparison, offsets, ties, invalid inputs and overflow; weighted costs and gold are supplied, not estimated corpus performance.
  • Four original SVGs bind actual output and raw data. Final isolated bilingual, three-width/four-font validation passed and desktop/mobile screenshots were inspected. Full article acceptance is recorded separately. Single-AI-author technical check, not independent human review; no upstream code copied or executed.
  • Post-registration correction: schema kind changed from invalid algorithm to concept. Exact body, code, equations, references and original six-file freeze preserved; production test-module shadowing fixed. Explicit correction diffs retained; repeat formal/content/build checks before publication acceptance.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.