from nltk.tree import *
np_trees = []
def traverse(t):
try:
t.label()
except AttributeError:
return
if t.label() == "VBZ":
current = t
while current.parent() is not None:
while current.left_sibling() is not None:
if current.left_sibling().label() == "NP":
np_trees.append(current.left_sibling())
current = current.left_sibling()
current = current.parent()
for child in t:
traverse(child)
tree = ParentedTree.fromstring("(S (NP (NNP)) (VP (VBZ) (NP (NNP))))")
traverse(tree)
print np_trees # [ParentedTree('NP', [ParentedTree('NNP', [])])]
基于你想做的,这应该行得通。它将首先给你最接近的左NP节点,然后是第二个最近的节点,依此类推。因此,如果你有一个}。在
(S (NP1) (VP (NP2) (VBZ)))
树,np_trees
列表将有{相关问题 更多 >
编程相关推荐