我不明白你为什么需要为此导入任何库/模块
import pprint # And ofcourse i import pprint just as i say that you dont need any importing, lol, this makes the printed dict look better in the terminal
matches = {}
# First store all the new sentences as a list
with open("test.txt", "r") as test:
new_sentences = test.read().split("\n")
# For checking without case sensitivity while also maintaining the original list
new_sentences_lower = [item.lower() for item in new_sentences]
# Second, store all the keys as a list
with open("test_oov.txt") as test_oov:
stored_keys = test_oov.read().split("\n")
# Again, to prevent case sensitivity and maintain original
stored_keys_lower = [item.lower() for item in stored_keys]
# i and j are the indices of key and sentence respectively
for i, key in enumerate(stored_keys_lower):
for j, sentence in enumerate(new_sentences_lower):
if key in sentence:
matches.update({stored_keys[i]: new_sentences[j]})
pprint.pprint(matches)
如果你希望每个键都有一个以上的例句,那么最好先把所有键和值列成一个列表
在上述代码中的for循环之前,您可以执行以下操作:
for key in stored_keys:
matches.update({key: []})
这将返回(使用pprint):
{'Joe biden': [],
'john mccain': [],
'johns hopkins university': [],
'johnson johnson': [],
'jpmorgan chase': [],
'justice department': [],
'kamala harris': [],
'kanye west': []}
在此之后,一个类似于之前的代码,除了我们在列表中附加了匹配的判决:
for i, key in enumerate(stored_keys_lower):
for j, sentence in enumerate(new_sentences_lower):
if key in sentence:
matches[stored_keys[i]].append(new_sentences[j])
pprint.pprint(matches)
最终输出:
{'Joe biden': ['joe biden is the us president'],
'john mccain': ['john mccain was a congressman'],
'johns hopkins university': [],
'johnson johnson': [],
'jpmorgan chase': ['jpmorgan chase is the way to go'],
'justice department': [],
'kamala harris': [],
'kanye west': ['kanye west is an artist']}