【问题标题】:NLTK: Getting rid of parentheses and pos- taggerNLTK:摆脱括号和后缀
【发布时间】:2014-03-21 04:27:14
【问题描述】:

我有这个代码。

from nltk import pos_tag, ne_chunk
import nltk.chunk
from nltk.corpus import names
qry = "who is Ronald Avon"
tokens = nltk.tokenize.word_tokenize(qry)
pos = nltk.pos_tag(tokens)
sentt = nltk.ne_chunk(pos, binary = False)
person = []
for subtree in sentt.subtrees(filter=lambda t: t.node == 'PERSON'):
    for leave in subtree.leaves():
        person.append(leave)
print "person=", person

它在一个句子中获取名称。这是我得到的结果。

person= [('Ronald', 'NNP'), ('Avon', 'NNP')]

我如何得到这样的结果:

Ronald
Avon

没有“NNP”和括号。谢谢。

【问题讨论】:

    标签: python nlp nltk pos-tagger


    【解决方案1】:

    使用列表推导。

    获取名称数组:

    names = [name for name, tag in person]
    

    以您提供的格式输出字符串:

    # Python 2 (print is a statement)
    print "\n".join([name for name, tag in person])
    
    # Python 3 (print is a function)
    print("\n".join([name for name, tag in person]))
    

    这确实是一个基本的 Python 数据结构问题 - 它并非特定于 NLTK。您可能会发现像 An informal guide to Python 这样的介绍性指南很有用。

    【讨论】:

    • 谢谢!仍然是一个 python 新手。我会看看那个链接。
    【解决方案2】:

    类似的东西?

    >>>for z in [i for i,y in person]: print z
    Ronald
    Avon
    >>>
    

    【讨论】:

      【解决方案3】:
      for subtree in sentt.subtrees(filter=lambda t: t.node == 'PERSON'):
          for name, tag in subtree.leaves():
              person.append(name)
      
      print('\n'.join(person))
      

      【讨论】:

        【解决方案4】:

        在不了解 NLTK 的情况下,您似乎不得不对返回数据的结构做出一些假设,即它是否始终是 2 元素元组的 2 元素列表。从外观上看,您可以这样做:

        person.append("%s %s" % (leave[0][0], leave[1][0]))
        

        如果您想打印“Ronald Avon”。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-04-05
          • 1970-01-01
          • 1970-01-01
          • 2016-07-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多