本文介绍了如何导航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")和右侧名词短语(基于Bristol的朋克摇滚乐队") .我该怎么办?
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?
发布评论