How to check if a key exists in a word2vec trained model or not How to check if a key exists in a word2vec trained model or not python python

How to check if a key exists in a word2vec trained model or not


Word2Vec also provides a 'vocab' member, which you can access directly.

Using a pythonistic approach:

if word in w2v_model.vocab:    # Do something

EDIT Since gensim release 2.0, the API for Word2Vec changed. To access the vocabulary you should now use this:

if word in w2v_model.wv.vocab:    # Do something

EDIT 2 The attribute 'wv' is being deprecated and will be completed removed in gensim 4.0.0. Now it's back to the original answer by OP:

if word in w2v_model.vocab:    # Do something


convert the model into vectors with

word_vectors = model.wv

then we can use

if 'word' in word_vectors.vocab


Answering my own question here.

Word2Vec provides a method named contains('view') which returns True or False based on whether the corresponding word has been indexed or not.