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.

Follow us on Facebook and Twitter for latest update.