【问题标题】:Navigate an NLTK tree (follow-up)导航 NLTK 树(后续)
【发布时间】:2015-05-07 12:15:57
【问题描述】:

我已经问过如何正确浏览 NTLK 树的问题。

如何正确浏览 NLTK 树(或 ParentedTree)?我想用父节点“VBZ”识别某个叶子,然后我想从那里进一步向上移动到树的左边来识别NP节点。

Original question

并提供以下说明:

我从 Tommy 那里得到了以下(非常有帮助的)答案(谢谢!):

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 树方面的专家,我很乐意与您聊天并支付几杯咖啡以换取一点见解。)

【问题讨论】:

    标签: python tree nlp nltk


    【解决方案1】:

    为此,我通常将子树功能与过滤器结合使用。 稍微改变你的树以表明它现在只选择一个 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 ))
    

    但是,当您的 subtree/x[0] 没有标签时(例如,当它是终端时),这可能会崩溃。或者当你的 NP 完全为空时抛出一个 IndexError 。但我会说这种情况不太可能发生。但是,很可能我正在监督这里的事情,你可能想要建立一些额外的检查......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 2017-04-30
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      相关资源
      最近更新 更多