分词与词元化:一个单位在哪里结束?
Tokenization
比较边界政策,保留字节与码点跨度,用动态规划求解加权词典切分。
tokenization数词之前,先决定在数什么单位
给一条文本处理管线输入下面这句虚构的测试文本:
Mina's café—AI costs 3.50.\t研究生命 👩💻
程序里的\t是一个制表符。按空白切分,会把café—AI和3.50.各自留成一个单位。识别标点的规则可以分开破折号和句号,但本文所选规则也会把小数拆成3、.、50。中文即使没有空格,也可能包含多个词。末尾显示成程序员的表情含三个码点:女性、零宽连接符和笔记本电脑。
词元是处理程序选定的单位。它可以是词、标点、子词、码点或字节。选定切分方法,也就选定了后续模型看到的单位。NLTK从边界选择和简单空白基线引入词元化;这里比较几种明确的原创政策,不预设一种政策适合所有语言。NLTK,词元化引入
本题从原字符串开始。文本规范化按照另一套政策改变字符串;词干提取与词形还原则在词元产生后变换或标注它们。计算偏移时,不应偷偷夹入这些变换。
边界要有单位,路径要有目标
能核对的词元记录
设字符串s含n个Unicode标量值,下标从0开始。第i个词元用码点半开区间[a_i,b_i)表示。区间非空、有序、互不重叠,可以留间隙:
半开表示包含a、不包含b,词元文本就是s[a:b]。只保存词元字符串,可能丢掉空格、制表符和换行。程序还保留每个词元前的间隙g_i及末尾g_tail,拼接才能还原原文:
重建检查实际拼接这些字段;把保存的raw字段与自己比较,验证不了任何切分行为。即使重建通过,边界仍可能不适合任务。把每个码点连空格一起各切一份,同样能还原。
UTF-8字节偏移使用另一套坐标。先算前缀字节长度B_j,再分别换算码点区间的两个端点:
Café有4个码点、5个UTF-8字节。在Café 研究中,中文词元占码点[5,7),却占字节[6,12)。要求字节偏移的标注程序,不能直接使用5和7。同样,每个字节未必能独立解码:Café最后两个字节为195和169,合起来才是é,各自严格解码都会失败。字节词元化需要约定如何解码拼接后的结果,不能假定每一片都是可打印字符。
三种可看清行为的政策
| 政策 | 规则 | 一个反例 |
|---|---|---|
| 码点 | Python字符串的每个元素各成一个词元 | 上面的表情变成三个单位,不是一个显示符号 |
| 空白 | 匹配每段非空白串 | 贴在词上的标点仍然贴着 |
| 本文正则 | 词字符串允许内部撇号,其余非空白标点或符号各成一个单位 | 3.50拆成三个词元,连续中文仍聚在一起 |
对于Unicode字符串,Python的\w包含Unicode字母数字字符及下划线,不表示“英文单词”或“完整语言学词”。CPython v3.12.4,re在本文模式下,分解形式的尖音符会单独成词元,预组合的é却能留在词字符串里。因此要记录是否先做了规范化。这里没有实现Unicode字素簇算法,也不声称符合UAX29。
把中文切分写成加权路径
用原创的小例子研究生命,提供下面这张词典:
| 词条 | 代价 |
|---|---|
| 研究 | 1 |
| 研究生 | 0.5 |
| 生命 | 1 |
| 命 | 4 |
在0到n的码点边界处放节点。只要s[i:j]是词条,就连接边(i,j),代价取词典给定值。每个位置还允许代价10的单码点回退;若该单字本来就在词典中,则使用词典代价。边始终向前,图没有环,而且每个位置都能到达。
最长匹配贪心地选择研究生 | 命,总代价4.5。另一切分研究 | 生命只需2。首词更长、局部代价更小,都不能证明整条路径更好。全局目标是:
令D(j)表示覆盖前j个码点的最低代价。到达j的最后一条边必然来自某个更早的i,因此:
按边界递增的顺序计算,每次改善代价时记住前驱。递推可由归纳说明:到j的最优路径,由其前驱处的最优前缀加最后一条边组成;若前缀更贵,换成便宜前缀就会改善整条路径。沿前驱回溯即可恢复切分。代码遇到相同总代价时保留遍历中先发现的路径;这是确定性的平局规则,不是从语言中学到的偏好。
设词典最长词长为L,候选子串位置有O(nL)个。在这个Python实现中,创建长度l的子串并计算哈希需要O(l),所以在哈希后的词典查询平均为常数时间的假设下,扫描最坏需O(nL²)时间。动态规划数组占O(n)空间;临时子串候选可能共占O(L²)个字符,输出及输入词典另计。前缀树能共享前缀扫描,但本程序没有这样实现。演示限制文本最多256码点、词典最多256条、每词最多64码点。
另行评估标注政策
假设明确指定的金标准是研究 | 生命。比较的是完整词元跨度,不是词元数量或还原后的原串。P和G分别表示同一原串上的预测、金标准跨度集合:
这个例子中,最长匹配得0,动态规划得1。共享句末端点,不等于共享一个完整词元跨度。教学评分器把零分母结果约定为0。这些数字只针对一个给定标注,不是真实语料准确率,也不衡量语义理解。换一种金标准政策,最优评分结果也可能改变。
运行边界记录和两条竞争路径
将下面完整程序保存为tokenization.py,运行python3 tokenization.py;仅依赖标准库。输入必须是不含代理码点的字符串。程序保留大小写、规范化形式、间隙及原文。词典示例拒绝空白和非有限代价;累计代价溢出时明确报错,不静默返回一条无穷代价路径。
"""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))
输出逐一列出词元文本、两套偏移和间隙,然后给出两种词典路径及指定金标准评分。三种政策的记录都能重建原输入。配套检查独立枚举短二元字符串的切分方式,对照动态规划最低代价,核对手算偏移,并覆盖空输入、回退、平局和非法跨度。这些有限检查只覆盖声明的程序,不构成通用分词器认证。
先决定应用最在意哪一种错误
检索索引可能希望拆开标点,财务抽取可能要求完整保留小数,跨度标注则需要稳定对应原串。空白基线容易检查,但发现不了连续中文内部的边界;正则增加了规则,却没有学习上下文。词典动态规划使用给定的可加代价。若把它们叫作概率,还需要另建规范化的模型,并说明参数如何估计。
学习得到的词或子词方法可以处理不同的词表取舍,但仍须交代训练文本、未知词政策、编码和解码。本篇不实现BPE、SentencePiece、形态切分或字素边界。宣称某个分词器更好之前,先确定标注政策和留出的任务评测。变换文本时保留与原文偏移的对应,分别检查能否重建和边界是否合适。
找出看似合理的边界规则会在哪里失效
Café 研究中,研究的两套偏移区间分别是什么?
答案:码点[5,7),UTF-8字节[6,12)。Café占5字节,后面的空格占1字节,每个中文字再占3字节。两组区间在不同单位下定位同一段文本。
- 只把
生命的代价从1改成4,其他词典内容不变。展示的两条路径中,哪条总代价较小?
答案:研究 | 生命变成5,研究生 | 命仍是4.5,这次贪心路径在比较中胜出。动态规划遵循给定代价,并没有把原金标准切分写死;本例的单码点回退路径仍更贵。
- 系统删掉空白并拼接词元字符串,却用保存的
raw字段等于输入来宣称成功。它缺少什么检查?
答案:要从实际保留的词元及间隙重建,再比较原文。两个原串副本相等,不能证明词元表示保存了制表符、重复空格或换行。即使真的能重建,也不能证明语言学边界正确。
- 人名识别器在NFC文本上训练,部署时收到带分解音符的文本,只修改跨度评分器够吗?
答案:不够。先对齐明确的规范化和词元化政策,并保留与原文标注的对应。本文正则可能把分解音符另切一份,在评分前就改变模型输入。只在相同原串、相同坐标单位上比较跨度,报告政策并评测未见样例。
借助库的定义,同时把政策选择说清楚
NLTK教材给出了从简单字符串处理过渡到词元化的讲解路径,固定版本的Python文档明确了这里依赖的\w含义。偏移记录、加权词典例子、独立枚举和评分约定是原创教学构造;两个来源都没有把这些数值报告成语言基准。下一题讨论不同词元被有意赋予同一个词干或词元基本形式时,会保留或丢掉什么。
先判断,再看解释
最长的首词代价0.5,余词代价4;另一切分的两个词各代价1。哪种切分使给定总代价最小?
学习目标
- 区分词元、码点与UTF-8字节。
- 用词元跨度及保留间隙重建原文。
- 推导并核对词典切分的最低总代价。
- 在明确标注政策下解释严格跨度F1。
先修与延伸
查看知识关联图 →参考文献
- NLTK Book: tokenization and normalization sections
Steven Bird; Ewan Klein; Edward Loper · 2026 - CPython v3.12.4: Unicode word characters in regular expressions
Python documentation contributors · 2024
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(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.
- 逐节对照两语:词元/字节/码点单位、有效区间、间隙和完整重建、Unicode正则局限、可加路径目标及最优子结构证明、O(nL²)子串工作量、给定金标准和零分母约定;六公式与四解释习题对应。
- 正式测试执行生产MDX:15项独立原型检查、改变代价的习题及6项出版检查,含穷举切分、偏移、平局、非法输入及溢出。代价与金标准明确给定,不是估计的语料性能。
- 四张原创SVG绑定真实输出与原数据;最终隔离双语、三宽/四字体验证通过,实际查看桌面/手机截图。完整文章验收另记。单AI作者技术检查,不是独立人工审校;无上游代码复制或执行。
- 登记后纠错:无效schema类型algorithm改为concept。正文、程序、公式、引用及原六文件冻结逐字保留;修正正式测试模块被局部变量遮蔽的问题。保留明确差异,重新通过正式、内容、构建检查后才确认出版验收。
核对的来源位置:
- NLTK Book: tokenization and normalization sections · Pinned ch03.rst lines1706–1768: lemma discussion and tokenization/whitespace introduction; not the entire chapter.
- CPython v3.12.4: Unicode word characters in regular expressions · Lines624–642: Unicode str word characters and ASCII/bytes differences; no linguistic-boundary guarantee.
相关主题