Using WordNet to find out whether two words are synonyms of each other

819 Views Asked by At

I'm having troubles with the loop. I need it to print 'synonyms' just once if any of the lemmas of that sense match with word2, otherwise 'not synonyms', but only once.

from nltk.corpus import wordnet as wn

word1 = 'motorcar'
word2 = 'automobile'

for syn in wn.synsets(word1):
    for lemma in syn.lemma_names():
        if lemma == word2 and lemma != word1:
            print('Synonyms')
        elif all(syn.lemma_names()) != word2:
            print('not synonyms')
3

There are 3 best solutions below

0
On

The usual pattern is to initialize a variable outside the loop, then report the result at the end of the loop. Something like this:

from nltk.corpus import wordnet as wn

word1 = 'motorcar'
word2 = 'automobile'

for syn in wn.synsets(word1):
    is_synonym = False
    for lemma in syn.lemma_names():
        if lemma == word2 and lemma != word1:
            is_synonym = True
    print('Synonyms' if is_synonym else 'not synonyms')
0
On

Same result but merging all the lemma lists in a single list named 'names' instead of using pivot boolean:

from nltk.corpus import wordnet as wn

word1 = 'motorcar'
word2 = 'automobile'

names = []
for syn in wn.synsets(word1):
    for lemma in syn.lemma_names():
        names.append(lemma)

print('Synonyms' if word2 in names else 'not synonyms')
0
On

I'm the author of the Python package WordHoard. This package can be used to find semantic relationships between words including a word's antonyms, synonyms, hypernyms, hyponyms and homophones.

from wordhoard import Synonyms

word1 = 'motorcar'
word2 = 'automobile'

synonym_list = Synonyms(word1).find_synonyms()
find_word = [word for word in synonym_list if word == word2]

if find_word is not None:
    print(f'{word2} is a synonym of {word1}')
    # print output
    automobile is a synonym of motorcar.
else:
    print(f'{word2} is not a synonym of {word1}')

I have found wordnet to be very limited. For instance these are the synonyms for motorcar from wordnet:

['auto', 'automobile', 'car', 'machine']

WordHoard is designed to query other sources. For example the query below returns 152 synonyms for the word motorcar.

from wordhoard import Synonyms

synonym_list = Synonyms('motorcar').find_synonyms()
print(len(synonym_list))
152

If you decided to use WordHoard please let me know how it works for your use case.