本守则的目的是通读下列句子:
test.txt
检查每个单词是否正确
test_oov.txt
有一个例句是
测验txt
一个示例输入文件是
joe biden is the us president
john mccain was a congressman
jpmorgan chase is the way to go
this is an irrelevant sentence
kanye west is an artist
测试一下。txt将是
joe biden
john mccain
johns hopkins university
johnson johnson
jpmorgan chase
justice department
kamala harris
kanye west
它应该是输出的
joe biden : joe biden is the us president
john mccain : john mccain was a congressman
etc.
然而,当
测试一下。txt
输入每行有多个单词。当一个单词只是一个单词时,它就很好用了。然而,如果是这样的话,
Joe Biden, or John mccain etc,
这不管用。
代码如下
from nltk.tokenize import sent_tokenize, word_tokenize
# 1. create a reusable word index like {'worda': [2, 4, 10], 'wordb': [1, 9]}
with open("test.txt", "r", encoding="utf8") as fp:
news_sentences = sent_tokenize(fp.read())
index = {}
for i, sentence in enumerate(news_sentences):
for word in word_tokenize(sentence):
word = word.lower()
if word not in index:
index[word] = []
index[word].append(i)
# 2. look up words from that index and retrieve the associated sentences
with open("test_oov.txt", "r", encoding="utf8") as fp:
oov_ner_data = [l.strip() for l in fp.readlines()]
matches = {}
for word in oov_ner_data:
word = word.lower()
if word in index:
matches[word] = [news_sentences[i] for i in index[word]]
for (key, value) in matches.items():
print(key + " : " + str(value))
我该怎么解决这个问题?