如何导航 nltk.tree.Tree? [英] How to navigate a nltk.tree.Tree?
本文介绍了如何导航 nltk.tree.Tree?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经使用了一个句子:
I've chunked a sentence using:
grammar = '''
NP:
{<DT>*(<NN.*>|<JJ.*>)*<NN.*>}
NVN:
{<NP><VB.*><NP>}
'''
chunker = nltk.chunk.RegexpParser(grammar)
tree = chunker.parse(tagged)
print tree
结果如下:
(S
(NVN
(NP The_Pigs/NNS)
are/VBP
(NP a/DT Bristol-based/JJ punk/NN rock/NN band/NN))
that/WDT
formed/VBN
in/IN
1977/CD
./.)
但现在我被困在试图弄清楚如何导航它.我希望能够找到 NVN 子树,并访问左侧名词短语(The_Pigs")、动词(are")和右侧名词短语(a Bristol-based punk rock band").我该怎么做?
But now I'm stuck trying to figure out how to navigate that. I want to be able to find the NVN subtree, and access the left-side noun phrase ("The_Pigs"), the verb ("are") and the right-side noun phrase ("a Bristol-based punk rock band"). How do I do that?
推荐答案
尝试:
ROOT = 'ROOT'
tree = ...
def getNodes(parent):
for node in parent:
if type(node) is nltk.Tree:
if node.label() == ROOT:
print "======== Sentence ========="
print "Sentence:", " ".join(node.leaves())
else:
print "Label:", node.label()
print "Leaves:", node.leaves()
getNodes(node)
else:
print "Word:", node
getNodes(tree)
这篇关于如何导航 nltk.tree.Tree?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文