python - NLTK:如何遍历名词短语以返回字符串列表?

标签 python parsing recursion nltk traversal

在 NLTK 中,如何遍历已解析的句子以返回名词短语字符串列表?

我有两个目标:
(1) 创建名词短语列表,而不是使用“traverse()”方法打印它们。我目前使用 StringIO 来记录现有 traverse() 方法的输出。这不是一个可接受的解决方案。
(2) 反解析名词短语字符串,这样:'(NP Michael/NNP Jackson/NNP)' 变成'Michael Jackson'。 NLTK 中有反解析的方法吗?

NLTK 文档建议使用 traverse() 来查看名词短语,但是如何在这种递归方法中捕获“t”以便生成字符串名词短语列表?

from nltk.tag import pos_tag

def traverse(t):
  try:
      t.label()
  except AttributeError:
      return
  else:
      if t.label() == 'NP': print(t)  # or do something else
      else:
          for child in t: 
              traverse(child)

def nounPhrase(tagged_sent):
    # Tag sentence for part of speech
    tagged_sent = pos_tag(sentence.split())  # List of tuples with [(Word, PartOfSpeech)]
    # Define several tag patterns
    grammar = r"""
      NP: {<DT|PP\$>?<JJ>*<NN>}   # chunk determiner/possessive, adjectives and noun
      {<NNP>+}                # chunk sequences of proper nouns
      {<NN>+}                 # chunk consecutive nouns
      """
    cp = nltk.RegexpParser(grammar)  # Define Parser
    SentenceTree = cp.parse(tagged_sent)
    NounPhrases = traverse(SentenceTree)   # collect Noun Phrase
    return(NounPhrases)

sentence = "Michael Jackson likes to eat at McDonalds"
tagged_sent = pos_tag(sentence.split())  
NP = nounPhrase(tagged_sent)  
print(NP)  

目前打印:
(NP迈克尔/NNP jackson /NNP)
(NP 麦当劳/NNP)
并将“无”存储到 NP

最佳答案

def extract_np(psent):
  for subtree in psent.subtrees():
    if subtree.label() == 'NP':
      yield ' '.join(word for word, tag in subtree.leaves())


cp = nltk.RegexpParser(grammar)
parsed_sent = cp.parse(tagged_sent)
for npstr in extract_np(parsed_sent):
    print (npstr)

关于python - NLTK:如何遍历名词短语以返回字符串列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33815401/

相关文章:

ios - 用于解析 fetchAllIfNeededInBackground 的 Swift 2 语法

linux - 比较文件夹中的所有文件

python - 如何提高这个递归函数的性能?

python - 类型错误:* 不支持的操作数类型: 'NoneType' 和 'int'

java - 尝试使用递归提出解决方案

python - 如何深入比较 Python 中的嵌套类型

Python Pandas 和正则表达式使用字典替换 Dataframe 中的项目

c - 解析 C 中同一字段中有多个空格的行

python - 按列汇总按组排名

python - 是否可以在单个 python 脚本中在多个 GPU 上并行训练多个 Keras 模型?