对于 NLTK 3.0,您希望使用 ParentedTree 子类。
http://www.nltk.org/api/nltk.html#nltk.tree.ParentedTree
使用您提供的示例树,创建 ParentedTree 并搜索您想要的节点:
from nltk.tree import ParentedTree
ptree = 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 ParentedTree
ptree = 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)