如何正确导航NLTK解析树?

2024-09-28 23:41:30 发布

您现在位置:Python中文网/ 问答频道 /正文

NLTK又把我逼疯了。在

如何在NLTK树(或ParentedTree)中正确导航? 我想用父节点“VBZ”来标识某个叶,然后我想从那里移到树的更高层,再向左移动,以标识NP节点。在

我该怎么做?NLTK树类似乎没有被考虑。。。或者我太蠢了。。。在

谢谢你的帮助!在

Tree


Tags: 节点np标识nltk高层树类vbzparentedtree
1条回答
网友
1楼 · 发布于 2024-09-28 23:41:30

基于你想做的,这应该行得通。它将首先给你最接近的左NP节点,然后是第二个最近的节点,依此类推。因此,如果你有一个(S (NP1) (VP (NP2) (VBZ)))树,np_trees列表将有{}。在

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', [])])]

相关问题 更多 >