0
NLTK再次讓我瘋狂。如何正確導航NLTK解析樹?
如何正確瀏覽NLTK樹(或ParentedTree)? 我想識別一個具有父節點「VBZ」的特定葉子,然後我想從那裏進一步向上移動並向左移動以識別NP節點。
我該怎麼做? NLTK樹類似乎不被認爲是通過...或者我太笨了...
感謝您的幫助!
NLTK再次讓我瘋狂。如何正確導航NLTK解析樹?
如何正確瀏覽NLTK樹(或ParentedTree)? 我想識別一個具有父節點「VBZ」的特定葉子,然後我想從那裏進一步向上移動並向左移動以識別NP節點。
我該怎麼做? NLTK樹類似乎不被認爲是通過...或者我太笨了...
感謝您的幫助!
根據你想做的事,這應該工作。它會給你最接近的左NP節點,然後第二個最接近的,所以,如果你有一棵(S (NP1) (VP (NP2) (VBZ)))
樹,你的np_trees
列表將有[ParentedTree(NP2), ParentedTree(NP1)]
。
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', [])])]
非常感謝你!我仍然在理解你在那裏做了什麼。 也有可能尋找一個特定的VBZ(與某一葉)? 因爲我不能給你投票(我沒有足夠的聲望),我可以以某種方式爲你買一杯咖啡嗎? – pascal
通過這樣做,正確嗎?如果t.label()==「VBZ」和t.leaves()[0] ==「does」:' (假設「does」是VBZ) – pascal
Tommy,我怎麼能包括條件NP下的節點必須是NNP?你的幫助將會非常感激! – pascal