我试图在通过处理语料库(文本文件 A)创建 gensim 模型后查找相关词。接下来,我想传递我自己的单词列表(存储的文本文件 B),以从 gensim 模型中获取与文本文件 B 中最相似的单词。
model = gensim.models.Word2Vec(documents, window=5, min_count=1, workers=10)
model.train(documents, total_examples=len(documents), epochs=10)
w1 = "beautiful"
print(model.wv.most_similar(positive=w1))
这给了我一个与单词“beautiful”相关的前 10 个单词的列表。但是,当我尝试传递我的列表(文本文件 B)时,它出现 key 错误: key 不存在。
mywords = read_med_terms("C:/Users/x/TextfileB.txt")
for word in mywords:
try:
print(model.wv.most_similar(positive=word))
except KeyError:
continue
如何通过我的列表来获取语料库中可用的相关匹配词集?衷心感谢您的帮助。
最佳答案
问题已经通过像这样使用异常try-except解决了:
relatedwords = []
for word in mywords:
try:
similar = model.wv.most_similar(positive=word)
v = [x[0] for x in similar]
relatedWords += v
except:
continue
关于python - 如何在python中使用gensim获取相关的匹配词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66930434/