0
我問過我如何正確導航通過NTLK樹。導航NLTK樹(後續)
如何正確瀏覽NLTK樹(或ParentedTree)?我想用父節點「VBZ」來標識某個葉子,然後我想從那裏進一步向上移動並向左移動以標識NP節點。
並提供瞭如下圖所示:
我從湯米以下(非常有用)答案(謝謝!):
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', [])])]
但我怎麼能包括th我只提取那些有NNP子節點的NP節點?
任何幫助將不勝感激。
(一般情況下,如果在你們中間NLTK樹木任何專家,我很想跟你聊天,以換取一些真知灼見交幾個咖啡。)