将依赖项解析的输出转换为树 [英] Converting output of dependency parsing to tree

查看:223
本文介绍了将依赖项解析的输出转换为树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Stanford dependency parser,并且我得到了句子的以下输出

I am using Stanford dependency parser and the I get the following output of the sentence

我在睡觉时射杀了大象

I shot an elephant in my sleep

python dep_parsing.py 
[((u'shot', u'VBD'), u'nsubj', (u'I', u'PRP')), ((u'shot', u'VBD'), u'dobj', (u'elephant', u'NN')), ((u'elephant', u'NN'), u'det', (u'an', u'DT')), ((u'shot', u'VBD'), u'nmod', (u'sleep', u'NN')), ((u'sleep', u'NN'), u'case', (u'in', u'IN')), ((u'sleep', u'NN'), u'nmod:poss', (u'my', u'PRP$'))]

我想将其转换为图,节点是每个令牌,边是它们之间的关系.

我需要进行进一步处理的图形结构,因此如果对它的修改容易并且也必须易于表示,将很有帮助.

I need the graph structure for further processing hence it would help if modification to it are easy and also must be easily representable.

到目前为止,这是我的代码.

Here is my code till now.

from nltk.parse.stanford import StanfordDependencyParser
stanford_parser_dir = 'stanford-parser/'
eng_model_path = stanford_parser_dir  + "stanford-parser-models/edu/stanford/nlp/models/lexparser/englishRNN.ser.gz"
my_path_to_models_jar = stanford_parser_dir  + "stanford-parser-3.5.2-models.jar"
my_path_to_jar = stanford_parser_dir  + "stanford-parser.jar"

dependency_parser = StanfordDependencyParser(path_to_jar=my_path_to_jar, path_to_models_jar=my_path_to_models_jar)

result = dependency_parser.raw_parse('I shot an elephant in my sleep')
dep = result.next()
a = list(dep.triples())
print a

如何制作这样的图形结构?

How can I make such a graph structure?

推荐答案

您可以遍历dep.triples()并获得所需的输出.

You can traverse over dep.triples() and get your desired output.

代码:

for triple in dep.triples():
    print triple[1],"(",triple[0][0],", ",triple[2][0],")"

输出:

nsubj ( shot ,  I )
dobj ( shot ,  elephant )
det ( elephant ,  an )
nmod ( shot ,  sleep )
case ( sleep ,  in )
nmod:poss ( sleep ,  my )

有关更多信息,您可以检查: NLTK Dependencygraph 方法to_dot()dep.tree().draw()

For more information you can check : NLTK Dependencygraph methods triples(), to_dot() and dep.tree().draw()

编辑-

dep.to_dot()的输出是

digraph G{
edge [dir=forward]
node [shape=plaintext]

0 [label="0 (None)"]
0 -> 2 [label="root"]
1 [label="1 (I)"]
2 [label="2 (shot)"]
2 -> 4 [label="dobj"]
2 -> 7 [label="nmod"]
2 -> 1 [label="nsubj"]
3 [label="3 (an)"]
4 [label="4 (elephant)"]
4 -> 3 [label="det"]
5 [label="5 (in)"]
6 [label="6 (my)"]
7 [label="7 (sleep)"]
7 -> 5 [label="case"]
7 -> 6 [label="nmod:poss"]
}

这篇关于将依赖项解析的输出转换为树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆