【问题标题】:How to get a binary parse in Python如何在 Python 中获取二进制解析
【发布时间】:2018-06-09 03:07:18
【问题描述】:

我有来自自然语言推理语料库(SNLImultiNLI)的数据,这些数据以这种形式出现:

'( ( Two ( blond women ) ) ( ( are ( hugging ( one another ) ) ) . ) )'

它们应该是二叉树(有些不是很干净)。

我想把我自己的一些句子解析成这种格式。我如何使用 NLTK 或类似工具来做到这一点?

我找到了 StanfordParser,但我还没有找到如何获得这种解析。

【问题讨论】:

    标签: python nlp nltk


    【解决方案1】:

    任何树都可以转换为保留其组成部分的二叉树。这是一个适用于nltk.Tree 输入的简单解决方案:

    from nltk import Tree
    from functools import reduce
    
    def binarize(tree):
        """
        Recursively turn a tree into a binary tree.
        """
        if isinstance(tree, str):
            return tree
        elif len(tree) == 1:
            return binarize(tree[0])
        else:
            label = tree.label()
            return reduce(lambda x, y: Tree(label, (binarize(x), binarize(y))), tree)
    

    如果您想要普通元组而不是 Tree,请将最后一个 return 语句替换为:

    return reduce(lambda x, y: (binarize(x), binarize(y)), tree)
    

    例子:

    >>> t = Tree.fromstring('''(ROOT (S (NP (NNP Oracle))
        (VP (VBD had) (VP (VBN fought) (S (VP (TO to)
          (VP (VB keep) (NP (DT the) (NNS forms))
            (PP (IN from) (S (VP (VBG being) (VP (VBN released))))))))))))''')
    
    >>> bt = binarize(t)
    
    >>> print(t)
    (ROOT
      (S
        (NP (NNP Oracle))
        (VP
          (VBD had)
          (VP
            (VBN fought)
            (S
              (VP
                (TO to)
                (VP
                  (VB keep)
                  (NP (DT the) (NNS forms))
                  (PP (IN from) (S (VP (VBG being) (VP (VBN released))))))))))))
    >>> print(bt)
    (S
      Oracle
      (VP
        had
        (VP
          fought
          (VP
            to
            (VP (VP keep (NP the forms)) (PP from (VP being released)))))))
    

    这将确保二进制结构,但不一定是正确的结构。大覆盖解析器会生成非二进制分支,因为某些附件选择非常困难。 (考虑经典的“我看到带望远镜的女孩”;PP“带望远镜”在物体内部,还是 VP 的一部分?)。所以请谨慎行事。

    【讨论】:

    • 非常感谢您的帮助,亚历克西斯。
    猜你喜欢
    • 2014-11-12
    • 2016-11-10
    • 2022-06-25
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多