<p>首先,如果您只是为Stanford CoreNLP依赖性解析器使用预先训练的模型,那么应该使用<code>CoreNLPDependencyParser</code>from{<cd2>}并避免使用旧的<code>nltk.parse.stanford</code>接口。在</p>
<p>见<a href="https://stackoverflow.com/questions/13883277/stanford-parser-and-nltk/51981566#51981566">Stanford Parser and NLTK</a></p>
<p>在终端下载并运行Java服务器后,在Python中:</p>
<pre><code>>>> from nltk.parse.corenlp import CoreNLPDependencyParser
>>> dep_parser = CoreNLPDependencyParser(url='http://localhost:9000')
>>> sent = "I shot an elephant with a banana .".split()
>>> parses = list(dep_parser.parse(sent))
>>> type(parses[0])
<class 'nltk.parse.dependencygraph.DependencyGraph'>
</code></pre>
<p>现在我们看到解析的类型是<code>DependencyGraph</code>,来自<code>nltk.parse.dependencygraph</code><a href="https://github.com/nltk/nltk/blob/develop/nltk/parse/dependencygraph.py#L36" rel="nofollow noreferrer">https://github.com/nltk/nltk/blob/develop/nltk/parse/dependencygraph.py#L36</a></p>
<p>要将<code>DependencyGraph</code>转换为<code>nltk.tree.Tree</code>对象,只需执行<code>DependencyGraph.tree()</code>操作:</p>
^{pr2}$
<p>要将其转换为方括号内的解析格式:</p>
<pre><code>>>> print(parses[0].tree())
(shot I (elephant an) (banana with a) .)
</code></pre>
<p>如果您正在寻找依赖关系三元组:</p>
<pre><code>>>> [(governor, dep, dependent) for governor, dep, dependent in parses[0].triples()]
[(('shot', 'VBD'), 'nsubj', ('I', 'PRP')), (('shot', 'VBD'), 'dobj', ('elephant', 'NN')), (('elephant', 'NN'), 'det', ('an', 'DT')), (('shot', 'VBD'), 'nmod', ('banana', 'NN')), (('banana', 'NN'), 'case', ('with', 'IN')), (('banana', 'NN'), 'det', ('a', 'DT')), (('shot', 'VBD'), 'punct', ('.', '.'))]
>>> for governor, dep, dependent in parses[0].triples():
... print(governor, dep, dependent)
...
('shot', 'VBD') nsubj ('I', 'PRP')
('shot', 'VBD') dobj ('elephant', 'NN')
('elephant', 'NN') det ('an', 'DT')
('shot', 'VBD') nmod ('banana', 'NN')
('banana', 'NN') case ('with', 'IN')
('banana', 'NN') det ('a', 'DT')
('shot', 'VBD') punct ('.', '.')
</code></pre>
<hr/>
<p>CONLL格式:</p>
<pre><code>>>> print(parses[0].to_conll(style=10))
1 I I PRP PRP _ 2 nsubj _ _
2 shot shoot VBD VBD _ 0 ROOT _ _
3 an a DT DT _ 4 det _ _
4 elephant elephant NN NN _ 2 dobj _ _
5 with with IN IN _ 7 case _ _
6 a a DT DT _ 7 det _ _
7 banana banana NN NN _ 2 nmod _ _
8 . . . . _ 2 punct _ _
</code></pre>