gpt4 book ai didi

python - 如何根据每个句子而不是通过文件来匹配命名实体

转载 作者:太空宇宙 更新时间:2023-11-03 21:02:58 24 4
gpt4 key购买 nike

我有一个文本文件,我实现了 Polyglot NER 来从此文本文件中提取实体。然后我必须对每个句子进行分段并匹配每个句子上提取的实体。匹配时它应该给我输出。

from polyglot.text import Text
file = open('input_raw.txt', 'r')
input_file = file.read()
file = Text(input_file, hint_language_code='fa')

def return_match(entities_list, sentence): ## Check if Chunks
for term in entities_list: ## are in any of the entities
## Check each list in each Chunk object
## and see if there's any matches.
for entity in sentence.entities:
if entity == term:
return entity
return None

def return_list_of_entities(file):
list_entity = []
for sentence in file.sentences:
for entity in sentence.entities:
list_entity.append(entity)
return list_entity

list_entity = return_list_of_entities(file)
#sentence_number = 4 # Which sentence to check
for sentence in range(len(file.sentences)):
sentencess = file.sentences[sentence]


match = return_match(list_entity, sentencess)

if match is not None:
print("Entity Term " + str(match) +
" is in the sentence. '" + str(sentencess)+ "'")
else:
print("Sentence '" + str(sentencess) +
"' doesn't contain any of the terms" + str(list_entity))


输入文件:

Bill Gates is the founder of Microsoft.
Trump is the president of the USA.
Bill Gates was a student in Harvard.

当我们实现 NER 时,实体如下所示:

列表实体:

Bill Gates, Microsoft, Trump, USA, Bill Gate, Harvard

当我们将实体与第一句匹配时,它给出:

当前输出:

(Bill Gates, Bill Gates, Microsoft)

预期输出:

(Bill Gates, Microsoft) # this is from the first sentence and should contine
(Trump, USA)
(Bill Gates, Harvard)

最佳答案

from polyglot.text import Text
import json
file = open('input_raw.txt', 'r')
input_file = file.read()
file = Text(input_file, hint_language_code='fa')

result = set()
entities_with_tag = []
def return_match(entities_list, sentence): # Check if Chunks
for i in range(len(sentence.entities)):
for j in range(len(entities_list)):
if entities_list[j] == sentence.entities[i]:
# result.append(sentence.entities[i])
result.add(str(sentence.entities[i]))
entities_with_tag.append(sentence.entities[i])

def return_list_of_entities(file):
list_entity = []
for sentence in file.sentences:
for entity in sentence.entities:
list_entity.append(entity)
return list_entity

list_entity = return_list_of_entities(file)

def return_sentence_number():
for i in range(len(file.sentences)):
sentence_no = file.sentences[i]
return sentence_no

sent_no = return_sentence_number()
return_match(list_entity, sent_no)
print("Entity Term " + str(result) + " is in the sentence. '" + str(sent_no) + "'")

关于python - 如何根据每个句子而不是通过文件来匹配命名实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55610352/

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