How to get related matching words using gensim in python?

Viewed 1699

I am trying to find related words after creating a gensim model by processing a corpus (Text file A). Next I want to pass my own list of words (stored Text file B) to get most similar words to those in Text file B from the gensim model.

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))

This gives me a list of top 10 correlated words to the word "beautiful".However, when I am trying to pass my list (text file B), it gets key error: key not present.

mywords = read_med_terms("C:/Users/x/TextfileB.txt")


for word in mywords:
    try:
        print(model.wv.most_similar(positive=word))
    except KeyError:
        continue

How can I pass my list to get the set of related matching words available in the corpus? Sincerely appreciate your help.

1 Answers

The problem has been solved by using the exception try-except like this:

relatedwords = []

for word in mywords:
    try:
        similar = model.wv.most_similar(positive=word)
        v = [x[0] for x in similar]
        relatedWords += v
    except:
        continue
Related