【问题标题】:extracting text from python Regexparser [duplicate]从python Regexparser中提取文本[重复]
【发布时间】:2018-11-04 11:24:43
【问题描述】:

我是 NLTK

的新手

这是我用过的代码,

text="The pizza was 66 and brilliant"
pattern = r"""
P: {<NN>+<VBD>+<CD>+}
"""
for sent in sent_tokenize(text):
  sentence = sent.split()
  PChunker = RegexpParser(pattern)
  output= PChunker.parse(pos_tag(sentence))
  print(output)

我得到了输出,

(S The/DT (P pizza/NN was/VBD 66/CD) and/CC brilliant/VB)

我需要输出,

pizza was 66

我怎样才能得到这个?

【问题讨论】:

  • 看起来output 是一种匹配对象。文档是否有关于如何从中获取匹配文本的任何信息?
  • 我没有找到任何相关信息

标签: python regex python-3.x nltk


【解决方案1】:

RegexpParser.parse 的输出是一棵树,您可以使用 tree.subtrees 循环遍历它。尝试以下操作,立即过滤您感兴趣的非终端节点(在您的情况下为 P):

from nltk import sent_tokenize
from nltk import RegexpParser
from nltk import pos_tag

text="The pizza was 66 and brilliant"
pattern = r"""
P: {<NN>+<VBD>+<CD>+}
"""
for sent in sent_tokenize(text):
  sentence = sent.split()
  PChunker = RegexpParser(pattern)
  output= PChunker.parse(pos_tag(sentence))
  print(output)
  for subtree in output.subtrees(filter=lambda t: t.label() == 'P'):
      print(subtree)
      print(' '.join([x[0] for x in subtree]))

【讨论】:

  • 这正是我所需要的。非常感谢。
  • 您好伊戈尔,我还有一个疑问。是否可以直接在模式中添加“是”。我正在尝试这样的示例。
猜你喜欢
  • 1970-01-01
  • 2012-02-09
  • 2016-10-20
  • 2012-08-31
  • 2019-12-16
  • 2019-06-29
  • 2018-11-20
  • 1970-01-01
相关资源
最近更新 更多