语言结构:同一句话,两种附着
Linguistic structure
用两棵给定树与完整结构检查程序,区分形态、成分、依存、意义和上下文。
linguistic-structure无人机跟谁在一起?
读一句虚构英文:Maya photographed the scientist with the drone。可能是 Maya 用无人机拍照,也可能是那位科学家身边带着无人机。单靠这些词,不能强制选定一种解释。把 with the drone 接到拍照的短语上,或接到科学家的短语上,就能让区别显现。
语言结构提供表示这类区别的方法。形态特征描述词形的属性,句法描述组合及语法关系,语义关乎解释,语用则考察具体使用情境中的语言。这些问题会相互影响,不保证计算机总按一条固定流水线逐一解决。
下面的程序接收两种预先提供的分析,检查它们的结构。它不发现解析、不排序,也不声称穷尽句子的解释。打印出一棵看似正确的树,不足以证明解析器能从未知文本中选出它。
先表示区别,再尝试消歧
形态:一个词形可以保留多个特征值
小型英语词表允许 fish 是单数或复数。在声明的第三人称现在时范围内,swims 要求单数,swim 要求复数。把约束结合起来,就选出一种读法:
程序还把 cat 记为单数、cats 记为复数。它查的是小型特征词表,不是在发现词干或切分后缀。UD 将 Number 描述为其分布和一致关系依赖具体语言的特征,取值并不限于本文的两个教学值。UD Number
更一般地,每个特征 k 对应一个有限的允许值集合。本文对约束 A、B 使用受限的合一操作:
这适用于双方都指定 k 的情况。缺省特征不增加约束;任何共享特征的交集为空,组合就失败。这是有限域约束求交,不是带变量、重入和出现检查的完整合一算法。
于是 fish swim 得到 Plur,fish swims 得到 Sing,cat swim 在此词表下没有读法。最后一句远窄于“程序证明所有这种形状的句子都不合语法”。I swim 不在词表内,而且需要区别人称;拒绝这个输入是范围限制,不是英语语法判决。
成分:哪些词构成一组?
成分表示递归地把词组织成组。本文常用缩写 S 表示句子,NP 表示名词短语,VP 表示动词短语,PP 表示介词短语。上下文无关文法可以规定允许的展开,树则记录一种具体结构。程序存储树,但不拿树与给定文法进行匹配。SLP 成分句法章节,定义与括号表示
两种给定结构的简写为:
Verb attachment: S(NP Maya, VP(photographed, NP the scientist, PP with the drone))
Noun attachment: S(NP Maya, VP(photographed, NP(NP the scientist, PP with the drone)))
第一行是动词附着,第二行是名词附着。实际程序还包含词汇标签,并打印完整括号串。两棵树的叶序列都是同样的七个词元:
index: 0 1 2 3 4 5 6
word: Maya photographed the scientist with the drone
每个节点有半开跨度 [a,b),包括 a、不包括 b:
两棵树里的 PP 都占 [4,7),长度为三;但只有名词附着树里存在覆盖 [2,7) 的 NP。两棵树的整句跨度都是 [0,7)。所以,叶序列相同不表示树相同,变化的分组正是需要保留的信息。
依存:哪个词连接到哪个中心词?
基本依存表示采用有标签的词间关系。UD 区分基本树与可以形成更一般图结构的增强依存。本检查器只处理基本树。UD 句法概览
采用从零开始的词索引,用 −1 作为人工 ROOT 目标。每个词 i 有一个中心词 h_i:
此外还必须无环。有限集合里的中心词追踪,要么到达 −1,要么重复某个节点。排除重复、要求唯一根后,每个词才能连接到那个根。只数根的数量不够,另一个连通部分可能自成环。
两种分析里,词 1(photographed)都是根,Maya 的关系是 nsubj,scientist 的关系是 obj。变化发生在最后一个中心词:
| 分析 | 索引0至6的中心词 | drone 的关系 | 最大词深度 |
|---|---|---|---|
| 动词附着 | [1,-1,3,1,6,6,1] | photographed 的 obl | 2 |
| 名词附着 | [1,-1,3,1,6,6,3] | scientist 的 nmod | 3 |
两个 the 的关系是 det;with 以 case 关系接到 drone。两组数组都包含六条词间边和一个根条目。这采用给定的 UD 风格实词中心分析;这里的索引不是 CoNLL-U 文件中从一开始的编号。UD 句法,实词与功能词
依存关系记录的是标注决定。本程序的 obl 不自动表示“工具”,nmod 也不表示“拥有”。annotation_view 返回主语、宾语、斜格成分和名词修饰语,没有把它们直接改名为施事、受事或所有者。
语义:在什么条件下,这句话才为真?
一种使解释明确的方法,是规定实体论域与已经解释的关系,再相对于这个模型求公式的值。公式在句法上合法,不等于它为真。NLTK 语义章节讲解这一区别,也说明变量赋值的作用。NLTK,Truth in Model 与 Individual Variables
在本文另设的简单思想实验中,P 是人之间的“拍摄了”关系。关于 Maya m 与科学家 s 的陈述为真,当且仅当这个有序对属于该关系:
要表达任一种无人机解释,还需另设工具关系或伴随关联。这项信息既不由人之间的有序对提供,也没有被中心词数组证明。这里没有实现语义解析器,也不声称小型关系表示能覆盖整句话的一切意义。
语用:哪种情境,意指哪个对象?
即使选定附着位置,the scientist 和 the drone 仍可能需要上下文来确定指称。另设一句 Bring that drone here(把那架无人机带到这里):理解 that 和 here 需要话语发生情境的信息;它的使用意图还涉及说话者要求什么行动。语用学研究上下文与交际意图的这些作用。SEP Pragmatics,引言
语义和语用的边界存在争论。对于 NLP 实现,实际要求是交代能访问什么上下文,还有什么未解决。一棵语法树本身既不能确定现实中的哪架无人机,也不能授权行动。
用完整程序检查给定分析
保存为 linguistic_structure.py,运行 python3 linguistic_structure.py。程序仅使用 Python 标准库,记录环境为 Python 3.12.4;输出是树、跨度、依存边和特征交集,没有训练参数或网络访问。
"""Original structural ambiguity and agreement examples, not a trained parser.
Two supplied analyses of one sentence. Validates constituency yields/spans and
basic dependency trees; an annotation view does not assert real-world meaning.
"""
import json
import re
def node(label,*children):
return (label,tuple(children))
def tree_info(tree,expected_tokens=None):
if not isinstance(tree,tuple):raise ValueError('A labeled tuple root is required')
leaves=[];spans=[];parts=[]
def visit(current,depth):
if depth>64:raise ValueError('Teaching tree depth limit exceeded')
if isinstance(current,str):
if not current or any(c.isspace() or c in '()' for c in current):raise ValueError('Each leaf must be one unbracketed token')
leaves.append(current);parts.append(current);return
if not isinstance(current,tuple) or len(current)!=2:raise ValueError('Nodes are (label, children) tuples')
label,children=current
if not isinstance(label,str) or not re.fullmatch(r'[A-Z][A-Z0-9-]*',label) or not isinstance(children,tuple) or not children:raise ValueError('Nonempty labeled nodes required')
begin=len(leaves);parts.append('('+label)
for child in children:parts.append(' ');visit(child,depth+1)
parts.append(')');spans.append([label,begin,len(leaves)])
visit(tree,0)
if expected_tokens is not None and tuple(leaves)!=tuple(expected_tokens):raise ValueError('Leaves do not match the supplied token sequence')
return {'tokens':leaves,'spans_half_open':spans,'brackets':''.join(parts)}
def dependency_info(heads,relations):
heads=list(heads);relations=list(relations);n=len(heads)
if not 1<=n<=256 or len(relations)!=n:raise ValueError('Equal, bounded, nonempty annotation arrays required')
if any(type(h) is not int or h < -1 or h>=n for h in heads):raise ValueError('Heads use zero-based word indices and -1 for ROOT')
if any(not isinstance(r,str) or not r for r in relations):raise ValueError('A relation is required for every word')
roots=[i for i,h in enumerate(heads) if h==-1]
if len(roots)!=1:raise ValueError('A basic dependency tree needs exactly one root word')
if any((h==-1)!=(r=='root') for h,r in zip(heads,relations)):raise ValueError('The root relation must match the ROOT edge')
maximum_depth=0
for start in range(n):
seen=set();current=start
while current!=-1:
if current in seen:raise ValueError('Dependency cycle')
seen.add(current);current=heads[current]
maximum_depth=max(maximum_depth,len(seen)-1)
return {'root':roots[0],'word_edges':n-1,'maximum_depth':maximum_depth,
'edges':[{'head':h,'dependent':i,'relation':relations[i]} for i,h in enumerate(heads) if h!=-1]}
def unify(left,right):
"""Intersect shared finite feature domains; an omitted feature is unconstrained."""
for mapping in [left,right]:
if not isinstance(mapping,dict):raise ValueError('Feature dictionaries required')
for key,values in mapping.items():
if not isinstance(key,str) or not key or not isinstance(values,(set,frozenset)) or not values or any(not isinstance(v,str) or not v for v in values):raise ValueError('Nonempty sets of feature values required')
result={}
for key in sorted(left.keys()|right.keys()):
values=left[key]&right[key] if key in left and key in right else left.get(key,right.get(key))
if not values:return None
result[key]=frozenset(values)
return result
def number_readings(noun,verb):
# A supplied third-person, present-tense English lexicon, not a universal rule.
nouns={'fish':['Sing','Plur'],'cat':['Sing'],'cats':['Plur']}
verbs={'swims':'Sing','swim':'Plur'}
if noun not in nouns or verb not in verbs:raise ValueError('Word outside the miniature lexicon')
results=[]
for value in nouns[noun]:
merged=unify({'Number':{value}},{'Number':{verbs[verb]}})
if merged is not None:results.append({key:sorted(v) for key,v in merged.items()})
return results
def examples():
subject=node('NP',node('PN','Maya'));verb=node('V','photographed')
scientist=node('NP',node('D','the'),node('N','scientist'))
drone=node('NP',node('D','the'),node('N','drone'));phrase=node('PP',node('P','with'),drone)
verb_attachment=node('S',subject,node('VP',verb,scientist,phrase))
noun_attachment=node('S',subject,node('VP',verb,node('NP',scientist,phrase)))
words=['Maya','photographed','the','scientist','with','the','drone']
return words,{'verb_attachment':verb_attachment,'noun_attachment':noun_attachment}
def annotations(attachment):
if attachment not in ['verb_attachment','noun_attachment']:raise ValueError('Unknown supplied reading')
return [1,-1,3,1,6,6,1 if attachment=='verb_attachment' else 3],['nsubj','root','det','obj','case','det','obl' if attachment=='verb_attachment' else 'nmod']
def annotation_view(words,heads,relations):
info=dependency_info(heads,relations)
if len(words)!=len(heads) or any(not isinstance(w,str) or not w for w in words):raise ValueError('One surface token per annotation required')
root=info['root']
def dependents(relation):return [words[i] for i,h in enumerate(heads) if h==root and relations[i]==relation]
return {'predicate_surface':words[root],'subjects':dependents('nsubj'),'objects':dependents('obj'),'obliques':dependents('obl'),
'nominal_modifiers':[{'head':words[h],'modifier':words[i]} for i,h in enumerate(heads) if h!=-1 and relations[i]=='nmod']}
def demo():
words,trees=examples();readings={}
for name,tree in trees.items():
heads,relations=annotations(name)
readings[name]={'constituency':tree_info(tree,words),'dependency':dependency_info(heads,relations),
'heads':heads,'relations':relations,'annotation_view':annotation_view(words,heads,relations)}
return {'sentence':' '.join(words),'tokens':len(words),'supplied_analyses':len(readings),'readings':readings,
'agreement':{noun+' '+verb:number_readings(noun,verb) for noun,verb in [('fish','swim'),('fish','swims'),('cat','swim'),('cats','swim')]},
'scope':'Two supplied analyses, not an exhaustive parse forest or a prediction. Basic dependency trees only; enhanced UD can be a graph. Surface subjects/objects are not automatically semantic agents/patients. Number lexicon is restricted to third-person present-tense English.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2))
tree_info 检查元组形状、非空节点标签、单词元叶子,以及叶序列与给定词元的一致性,并将深度限制为 64。这些检查确认表示格式良好,不确认它符合某个上下文无关文法。
dependency_info 检查 1–256 个中心词条目、整数范围、唯一根、根标签对应和无环。它不验证完整 UD 关系词表,也不分析增强边。最坏追踪成本为 O(n²),因为 n 个起点各自都可能走过一条长链,临时访问集合使用 O(n) 空间。这个直接方法适合声明的小输入,不宣称是最优依存验证器。
树遍历耗时与访问节点数及输出文本量成正比,保存叶表、跨度和括号输出。合一函数对共享特征做有限集合交集,对单边特征复制约束,并排序特征名以稳定输出。成本取决于这些域的大小,不是在整句解析空间里做指数搜索。
14 项测试覆盖两种给定读法、半开跨度、环/根失败、有限域一致、非法树及词表以外的词形。中文词也能存成树叶,但这种存储能力不表示英语一致规则适用于中文。草稿检查另外运行从双语 MDX 中提取的程序。
有了表示,不代表分析成功
分词器的边界决定哪些单位接受跨度与中心词标注。文本表示改变时,旧偏移和旧标注需要明确转换。文本规范化提供了变换字符串后跨度移动的实例。
不同标注体系可能以不同方式编码相关语言区别。应按选定体系和语言评测解析器,检查标注分歧,在任务允许时保留确有歧义的候选。短小的中心词数组不是普遍语法理论;UD 本身也讨论依存关系及跨语言平行性的限制。UD 句法概览
程序不从任意词形推断形态,不消解作用域或指称,不学习文法、不评分候选,也不使用视觉上下文。两种结构都是教学输入。推断这些结构的算法属于后续解析主题,完整 NLP 管线还需要任务与评测约定。
读懂结构,不替它编造意义
-
基本理解。动词附着分析中,drone 通过
obl接到 photographed。程序是否因此确认 Maya 用无人机当相机?答案:没有。它记录的是给定句法关系。工具解释需要额外语义决定及相应证据,代码没有实现这一步。
-
手算。按所列七个词元,[4,7) 有多长?哪种分析包含覆盖 [2,7) 的 NP?
答案:三个词元:with、the、drone。只有名词附着分析包含那个五词元 NP,两种分析的完整叶序列仍相同。
-
边界。为什么
fish swims有读法,cat swim却没有?第二个结果足以把I swim判成不合语法吗?答案:fish 允许 Sing 或 Plur,swims 选出 Sing;cat 提供 Sing,而受限 swim 词条要求 Plur,交集为空。
I不在词表内,还涉及人称区别,所以程序没有判断那句话的语法。 -
迁移。系统因为
[-1,2,1]恰好有一个根就接受了它,还漏了什么?修好检查是否就解决了that drone的意义?答案:词 1 与词 2 构成环,还需检查中心词追踪。拒绝这棵坏树修复的是结构约束;确定指示表达的指称,仍需另一项依赖上下文的解释步骤。
让每项资料支持它真正描述的层次
SLP 章节支持成分与文法记法,固定版本 UD 文档支持依存约定及 Number 特征,并保留语言差异。固定 NLTK 章节支持公式与模型中意义的区别;SEP 存档条目提供上下文与意图的学术概览,不是可执行的指称消解算法。
句子、树对、中心词数组、有限词表、关系思想实验和习题均为原创。范围保持可检查:两种给定分析、七个词元、六条词间边和一张小型一致表。不能从这些结果推断解析准确率、全面语言理论或人的理解分数。
先判断,再看解释
两棵树的叶序列相同,可以推出什么?
学习目标
- 区分词形特征、句法、解释与上下文。
- 比较同一词序列的两种结构。
- 验证跨度与基本依存树,不冒称已判定语法。
- 使用有限特征约束并保留具体语言限制。
先修与延伸
查看知识关联图 →参考文献
- Speech and Language Processing, constituency chapter, August 19 2026 draft
Daniel Jurafsky; James H. Martin · 2026 - Universal Dependencies syntax overview, pinned revision
Universal Dependencies contributors · 2026 - Universal Dependencies Number feature, pinned revision
Universal Dependencies contributors · 2026 - Natural Language Processing with Python, chapter 10, pinned source
Steven Bird; Ewan Klein; Edward Loper - Pragmatics, Stanford Encyclopedia of Philosophy, Summer 2026 archive
Kepa Korta; John Perry · 2024
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-08 · Codex single-AI-author technical check: scoped constituency, pinned UD features/dependencies, pinned model semantics and archived pragmatics; five paired equations, supplied trees/spans/heads, finite Number intersections, separation of annotation and meaning, four explained exercises and computed SVGs. Not a trained parser, exhaustive grammar, human peer review or full UD conformance. Production browser acceptance recorded separately.
- 逐节核对两语:形态与有限词表查找、缺省与空特征域、成分分组及半开跨度、基本中心词树的根/环约束、模型相对谓词和上下文指称;五个对应公式和四道解释习题。
- 14项结构/特征检查嵌入生产测试,另有6项出版检查;两种给定七词元分析、各六条词间边、实际深度2/3、更大NP只在名词附着、非法中心词/环、特征冲突及不支持的语言范围。
- 不检查CFG产生式,不训练解析器,不主张普遍英语一致规则,不自动解释工具或拥有关系。语义关系是原创思想实验,语用存档是学术概览,不是已执行的指称消解器。
- 四张原创SVG绑定真实输出与原数据;最终隔离双语、三宽/四字体验证通过,实际查看桌面/手机截图。完整文章验收另记。单AI作者技术检查,不是独立人工审校;无上游代码复制或执行。
核对的来源位置:
- Speech and Language Processing, constituency chapter, August 19 2026 draft · Scoped PDF text40–144 and191–195: constituents, grammar and brackets. No full chapter, parsing evaluation, historical attribution or visual PDF review.
- Universal Dependencies syntax overview, pinned revision · Pinned raw lines1–113, basic/enhanced representations and content/function word conventions. Not full UD conformance.
- Universal Dependencies Number feature, pinned revision · Pinned raw lines1–56; language-dependent feature distribution and Sing/Plur/Dual. Original lexicon is narrower.
- Natural Language Processing with Python, chapter 10, pinned source · Pinned chapter raw1011–1060 and1113–1128: model-relative meaning and assignments. No copied code/examples, full chapter reading or NLTK execution.
- Pragmatics, Stanford Encyclopedia of Philosophy, Summer 2026 archive · Archive metadata and introduction19–60; revision2024-05-28; authors614–616. Scholarly overview for context/intention, not original speech-act experiments or a complete survey review.
相关主题