簡體   English   中英

如何正確導航NLTK解析樹?

[英]How to properly navigate an NLTK parse tree?

NLTK再次讓我發瘋。

如何正確瀏覽NLTK樹(或ParentedTree)? 我想用父節點“ VBZ”標識某個葉子,然后我想從那里進一步向上移動到樹的左側,以標識NP節點。

我該怎么做呢? NLTK樹類似乎沒有被考慮...或者我太愚蠢了...

謝謝你的幫助!

樹

根據您要執行的操作,這應該可行。 它將首先為您提供最接近的左NP節點,然后為您提供第二個最接近的NP節點, np_trees 。因此,如果您有一棵(S (NP1) (VP (NP2) (VBZ)))np_trees ,則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', [])])]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM