【发布时间】:2020-09-03 09:02:45
【问题描述】:
当我读取文本文件以生成词嵌入向量时,我收到此错误:“KeyError:单词'restriction'不在词汇表中”,而单词'restrictions'在文本文件中。我想知道我读取文本文件(一个简单的段落)的代码是否错误?
我的代码写在下面:
from gensim.models import Word2Vec
# define training data
with open('D:\\test.txt', 'r') as file:
sentences = ""
#read from textfile
for line in file:
for word in line.split(' '):
sentences += word + ' '
# train model
model = Word2Vec(sentences, min_count=1)
# summarize the loaded model
print(model)
# summarize vocabulary
words = list(model.wv.vocab)
# save model
model.save('model.bin')
# load model
new_model = Word2Vec.load('model.bin')
print(new_model)
print(str(model['restriction']))
当我在代码中使用预先写好的句子时,不会出现此错误,如下所示:
from gensim.models import Word2Vec
# define training data
sentences = [['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec'],
['this', 'is', 'the', 'second', 'sentence'],
['yet', 'another', 'sentence'],
['one', 'more', 'sentence', 'with', 'restriction'],
['and', 'the', 'final', 'sentence']]
# train model
model = Word2Vec(sentences, min_count=1)
# summarize the loaded model
print(model)
# summarize vocabulary
words = list(model.wv.vocab)
print(words)
# access vector for one word
print(model['sentence'])
# save model
model.save('model.bin')
# load model
new_model = Word2Vec.load('model.bin')
print(new_model)
print('the model prints: ')
print(model['restriction'])
【问题讨论】:
-
首先,我会尝试取消缩进整个文件读取代码块。
标签: python deep-learning text-files word2vec