对于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)
此外,见http://stackoverflow.com/questions/16407880/extracting-specific-leaf-value-from-nltk-tree -structure-with-python?rq = 1 – Jesuisme 2014-09-22 14:45:39