我试图从依赖关系分析器的输出生成一个树(嵌套字典)。句子是“我在睡梦中射杀了一头大象”。我可以获得链接上描述的输出: How do I do dependency parsing in NLTK?
nsubj(shot-2, I-1)
det(elephant-4, an-3)
dobj(shot-2, elephant-4)
prep(shot-2, in-5)
poss(sleep-7, my-6)
pobj(in-5, sleep-7)
为了将这个元组列表转换成嵌套字典,我使用了以下链接: How to convert python list of tuples into tree?
^{pr2}$输出如下:
{'shot': (('ROOT', 'ROOT'),
{'I': (('nsubj', 'shot'), {}),
'elephant': (('dobj', 'shot'), {'an': (('det', 'elephant'), {})}),
'sleep': (('nmod', 'shot'),
{'in': (('case', 'sleep'), {}), 'my': (('nmod:poss', 'sleep'), {})})})}
为了找到根到叶的路径,我使用了以下链接:Return root to specific leaf from a nested dictionary tree
[创建树和查找路径是两件不同的事情]第二个目标是找到根到叶节点的路径,就像done Return root to specific leaf from a nested dictionary tree。
但是我想从根到叶(依赖关系路径)
因此,例如,当我调用recurse_category(categories,'an'),其中categories是嵌套的树结构,“an”是树中的单词,我应该得到ROOT-nsubj-dobj
(依赖关系到根)作为输出。在
这会将输出转换为嵌套字典形式。如果我也能找到路,我会随时通知你的。也许这个,是有帮助的。在
输出是一个嵌套字典
[{'Name': 'shot', 'Relationship': 'ROOT', 'children': [{'Name': 'I', 'Relationship': 'nsubj'}, {'Name': 'elephant', 'Relationship': 'dobj', 'children': [{'Name': 'an', 'Relationship': 'det'}]}, {'Name': 'sleep', 'Relationship': 'nmod', 'children': [{'Name': 'in', 'Relationship': 'case'}, {'Name': 'my', 'Relationship': 'nmod:poss'}]}]}]
以下函数可以帮助您找到根到叶的路径:
^{pr2}$首先,如果您只是为Stanford CoreNLP依赖性解析器使用预先训练的模型,那么应该使用}并避免使用旧的
CoreNLPDependencyParser
from{nltk.parse.stanford
接口。在见Stanford Parser and NLTK
在终端下载并运行Java服务器后,在Python中:
现在我们看到解析的类型是
DependencyGraph
,来自nltk.parse.dependencygraph
https://github.com/nltk/nltk/blob/develop/nltk/parse/dependencygraph.py#L36要将
^{pr2}$DependencyGraph
转换为nltk.tree.Tree
对象,只需执行DependencyGraph.tree()
操作:要将其转换为方括号内的解析格式:
如果您正在寻找依赖关系三元组:
CONLL格式:
相关问题 更多 >
编程相关推荐