对于NLTK 3.0,您想使用ParentedTree子类。
http://www.nltk.org/api/nltk.html#nltk.tree.ParentedTree
使用给定的示例树,创建ParentedTree并搜索所需的节点:
from nltk.tree import ParentedTreeptree = ParentedTree.fromstring('(ROOT (S (NP (PRP It)) (VP (VBZ is) (ADJP (RB so) (JJ nice))) (. .)))')leaf_values = ptree.leaves()if 'nice' in leaf_values: leaf_index = leaf_values.index('nice') tree_location = ptree.leaf_treeposition(leaf_index) print tree_location print ptree[tree_location]您可以直接遍历树以获取子树。parent()方法用于查找给定子树的父树。
这是一个为子代和父代使用更深树的示例:
from nltk.tree import ParentedTreeptree = ParentedTree.fromstring('(ROOT (S (NP (JJ Congressional) (NNS representatives)) (VP (VBP are) (VP (VBN motivated) (PP (IN by) (NP (NP (ADJ shiny) (NNS money))))))) (. .))')def traverse(t): try: t.label() except AttributeError: return else: if t.height() == 2: #child nodes print t.parent() return for child in t: traverse(child)traverse(ptree)


