【问题标题】:NLTK Turning a subtree into a list in python / RSS feed chunkingNLTK 在 python / RSS 提要分块中将子树转换为列表
【发布时间】:2013-10-20 00:20:26
【问题描述】:

使用下面的代码,我正在分块一个已经标记和标记化的 rss 提要。 “print subtree.leaves()”正在输出:

[('Prime', 'NNP'), ('Minister', 'NNP'), ('Stephen', 'NNP'), ('Harper', 'NNP')] [('U.S.', 'NNP'), ('President', 'NNP'), ('Barack', 'NNP'), ('Obama', 'NNP')] [('什么\','NNP')] [('Keystone', 'NNP'), ('XL', 'NNP')] [('CBC', 'NNP'), ('新闻', 'NNP')]

这看起来像一个 python 列表,但我不知道如何直接访问它或迭代它。我认为这是一个子树输出。

我希望能够将此子树转换为我可以操作的列表。是否有捷径可寻?这是我第一次在 python 中遇到树,我迷路了。我想以这个列表结束:

docs = [“总理斯蒂芬·哈珀”、“美国总统巴拉克·奥巴马”、“什么”、“Keystone XL”、“CBC 新闻”]

有没有一种简单的方法可以做到这一点?

谢谢,一如既往的帮助!

grammar = r""" Proper: {<NNP>+} """

cp = nltk.RegexpParser(grammar)
result = cp.parse(posDocuments)
nounPhraseDocs.append(result) 

for subtree in result.subtrees(filter=lambda t: t.node == 'Proper'):
# print the noun phrase as a list of part-of-speech tagged words

    print subtree.leaves()
print" "

【问题讨论】:

    标签: list parsing tree nltk chunks


    【解决方案1】:

    node 现在已被label 取代。所以修改Viktor's答案:

    docs = []
    
    for subtree in result.subtrees(filter=lambda t: t.label() == 'Proper'):
        docs.append(" ".join([a for (a,b) in subtree.leaves()]))
    

    这将为您提供仅属于Proper 夹头的那些令牌的列表。您可以从 subtrees() 方法中删除 filter 参数,您将获得属于树的特定父级的所有标记的列表。

    【讨论】:

      【解决方案2】:
      docs = []
      
      for subtree in result.subtrees(filter=lambda t: t.node == 'Proper'):
          docs.append(" ".join([a for (a,b) in subtree.leaves()]))
      
      print docs
      

      这应该可以解决问题。

      【讨论】:

        猜你喜欢
        • 2017-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-09
        • 1970-01-01
        • 2014-01-16
        相关资源
        最近更新 更多