如何从gensim获取word2index

Gab*_*Chu 10 gensim

已经将word2vec模型读入了genism

model = KeyedVectors.load_word2vec_format('word2vec.50d.txt', binary=False)
Run Code Online (Sandbox Code Playgroud)

似乎genism只提供了从索引到单词的映射,也就是说,model.index2word[2]我们怎样才能在此基础上派生出一个倒置字典(word2index)呢?

goj*_*omo 18

word-to-index的映射在KeyedVectors vocab属性中,是包含index属性的对象的字典.

例如:

word = "whatever"  # for any word in model
i = model.vocab[word].index
model.index2word[i] == word  # will be true
Run Code Online (Sandbox Code Playgroud)

  • API现在改变了,使用`model.wv.vocab.get(word).index` (6认同)