python - 直接以 NLTK 模式应用字符串

标签 python regex python-3.x nltk

我是 NLTK 新手, 我正在尝试从字符串中获取公司名称。这是我写的代码。但它没有给出输出。是否可以直接在模式中给出字符串值?谁能帮帮我吗。提前致谢

from nltk.tokenize import sent_tokenize, word_tokenize
from nltk import pos_tag,RegexpParser
text="CompanyName1 GmbH is from Germany. CompanyName2 Inc is from America. ComapnyName3 corp is from India."
pattern = r"""
P: {<NNP>+<GmbH|Inc|corp>}
"""
for sent in sent_tokenize(text):
   sentence = sent.split()
   print("Parts of speech :",pos_tag(sentence))
   PChunker = RegexpParser(pattern)
   output= PChunker.parse(pos_tag(sentence))
   for subtree in output.subtrees(filter=lambda t: t.label() == 'P'):
     # print(subtree)
     print(' '.join([x[0] for x in subtree]))

最佳答案

您可以在此处组合正则表达式和 NLTK 功能。

import re
...
text="CompanyName1 GmbH is from Germany. CompanyName2 Inc is from America. Comapny Name3 corp is from India."
for sent in  sent_tokenize(text):
    tagged = pos_tag(word_tokenize(sent))
    joined = ' '.join(["{}<{}>".format(word,tag) for word,tag in tagged])
    print([x.strip().replace("<NNP>", "") for x in re.findall(r'((?:\S+<NNP> )+)(?:GmbH|Inc|corp)<NN[^>]*>', joined)])
    print('-------- NEXT SENTENCE ----------')

输出:

['CompanyName1']
-------- NEXT SENTENCE ----------
['CompanyName2']
-------- NEXT SENTENCE ----------
['Comapny Name3']
-------- NEXT SENTENCE ----------

joined = ' '.join(["{}<{}>".format(word,tag) for word,tag in tagged])部分创建一个临时句子,并在单词上附加标签。正则表达式是 ((?:\S+<NNP> )+)(?:GmbH|Inc|corp)<NN[^>]*> ,它匹配

  • ((?:\S+<NNP> )+) - 捕获组 1(它将是 re.findall 的输出):1 个或多个非空白字符后跟 <NNP>和一个空格,全部重复 1 次或多次(由于 + )
  • (?:GmbH|Inc|corp) - 与 3 个替代项中的任何一个匹配的非捕获组( | 是替代运算符)
  • <NN[^>]*> - 一个<NN + 除 > 之外的任意 0 个或多个字符然后是 > .

要获得最终结果,应从公司名称中删除标签,因此您可以只使用 x.strip().replace("<NNP>", "") - 从找到的匹配项的开头/结尾去除空格并删除 <NNP>仅使用 str.replace 进行标记方法。

关于python - 直接以 NLTK 模式应用字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50559652/

相关文章:

python - 将任何 unicode 字符串转换为相应的虚拟键(扫描)代码

python - 将矩阵乘以Numpy中另一个矩阵的每一行

javascript 电子邮件正则表达式问题

python - 返回不同长度输出的笛卡尔积

python-3.x - 如何在moviepy中将音频输入为字节

python - 在 python 中格式化对象列表

python - Series 对象没有 split 属性 - 从文本文件读取数据

python - Keras:ValueError:logits 和标签必须具有相同的形状 ((None, 2) vs (None, 1))

java - 分隔符的正则表达式

带有反向引用的 Java String.replaceAll()