【问题标题】:How to properly navigate an NLTK parse tree?如何正确导航 NLTK 解析树?
【发布时间】:2015-05-06 04:13:26
【问题描述】:

NLTK 又把我逼疯了。

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

我该怎么做? NLTK树类好像没有经过深思熟虑……还是我太笨了……

感谢您的帮助!

【问题讨论】:

    标签: python tree nlp nltk


    【解决方案1】:

    根据您想要做的,这应该有效。它会首先为您提供最接近的左 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(带有特定叶子)?因为我不能投票给你(我没有足够的声望),我可以给你买杯咖啡吗?
    • 这样做,对吗? if t.label() == "VBZ" and t.leaves()[0] == "does":(假设“做”是VBZ)
    • 我必须检查 t.leaves() 的返回值,但是如果你希望 VBZ 只有一个“确实”的叶子,假设你从 leaves() 你得到一个数组应该这样做and t.leaves() == ["does"]。在没有叶子的情况下,这将处理叶子中只有一个单词而没有可能的索引越界异常。如果还有其他叶子,出于同样的原因,您可能想做and "does" in t.leaves()
    • 对于NNP子节点,当你找到NP节点时,只需检查NP节点的child(ren)是否有一个以NNP标签为根的子树。根据是否只能存在具有 NNP 的子树或多个子树和叶子,其中一个是 NNP,您搜索的方式会有所不同
    • 如果您需要我评论我的代码以帮助您理解它,请告诉我,我会编辑我的帖子
    猜你喜欢
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2013-10-04
    相关资源
    最近更新 更多