NLTK corpus: Find the sets of synonyms and antonyms of a given word

NLTK corpus: Exercise-7 with Solution

Write a Python NLTK program to find the sets of synonyms and antonyms of a given word.

From Wikipedia,
WordNet is a lexical database for the English language. It groups English words into sets of synonyms called synsets, provides short definitions and usage examples, and records a number of relations among these synonym sets or their members.

Sample Solution:

Python Code :

from nltk.corpus import wordnet
synonyms = []
antonyms = []

for syn in wordnet.synsets("end"):
    for l in syn.lemmas():
        if l.antonyms():
print("\nSet of synonyms of the said word:")
print("\nSet of antonyms of the said word:")

Sample Output:

Defination of the said word:
a hostile meeting of opposing military forces in the course of a war

Examples of the word in use::
['Grant won a decisive victory in the battle of Chickamauga', 'he lost his romantic ideas about war when he got into a real engagement']

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python NLTK program to find the definition and examples of a given word using WordNet.
Next: Write a Python NLTK program to get the overview of the tagset, details of a specific tag in the tagset and details on several related tagsets, using regular expression.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Share this Tutorial / Exercise on : Facebook and Twitter

Python: Tips of the Day

Get the Key Whose Value Is Maximal in a Dictionary:

>>> model_scores = {'model_a': 100, 'model_z': 198, 'model_t': 150}
>>> # workaround
>>> keys, values = list(model_scores.keys()), list(model_scores.values())
>>> keys[values.index(max(values))]
>>> # one-line
>>> max(model_scores, key=model_scores.get)