how to get synonyms of a word in python 1

how to get synonyms of a word in python

import nltk
from nltk.corpus import wordnet   #Import wordnet from the NLTK
syn = list()
ant = list()
for synset in wordnet.synsets("Worse"):
   for lemma in synset.lemmas():
      syn.append(lemma.name())    #add the synonyms
      if lemma.antonyms():    #When antonyms are available, add them into the list
      ant.append(lemma.antonyms()[0].name())
print('Synonyms: ' + str(syn))
print('Antonyms: ' + str(ant))

Here is what the above code is Doing:
1. We first import the wordnet from the nltk.corpus.
2. Then we create two empty lists, one for synonyms and one for antonyms.
3. We iterate through every synset in wordnet with the specific word as the parameter.
4. Then we iterate through every lemma in the synset.
5. We add the lemma to the synonym list.
6. If the lemma has an antonym, we add it to the antonym list.
7. We print the lists.

Similar Posts