导航NLTK树(后续)

2024-09-28 23:44:35 发布

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

我问过一个问题,我怎样才能在NTLK树中正确导航。在

How do I properly navigate through an NLTK tree (or ParentedTree)? I would like to identify a certain leaf with the parent node "VBZ", then I would like to move from there further up the tree and to the left to identify the NP node.

Original question

并提供了以下插图:

NLTK tree

我从汤米那里得到了以下(非常有帮助的)答案(谢谢!)公司名称:

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

但是我怎样才能包括我只提取那些具有NNP子节点的NP节点的条件呢?

如有任何帮助,我们将再次感谢。在

(一般来说,如果你们当中有什么关于NLTK树的专家,我很愿意和你聊聊天,并支付一些咖啡费,以换取一些见解。)


Tags: thetotreenpcurrentlefttreeslabel
1条回答
网友
1楼 · 发布于 2024-09-28 23:44:35

我通常将subtrees函数与过滤器结合使用。 稍微更改树以显示它现在只选择一个NP:

>>> tree = ParentedTree.fromstring("(S (NP (NNP)) (VP (VBZ) (NP (NNS))))")
>>> for st in tree.subtrees(filter = lambda x: x.label() == "NP" and x[0].label() == 'NNP'):
...     print(st)
... 
(NP (NNP ))

但是,当你的子树/x[0]没有标签时(例如,当它是终端时),这可能会崩溃。或者在NP完全为空时抛出索引器。但我认为这种情况不大可能发生。然而,很有可能我在监督这里的事情,你可能想建立一些额外的检查。。。在

相关问题 更多 >