gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:24:19 33 4
gpt4 key购买 nike

我是 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com