The Wayback Machine - https://web.archive.org/web/20240927030745/https://www.geeksforgeeks.org/get-synonymsantonyms-nltk-wordnet-python/
Open In App

How to get synonyms/antonyms from NLTK WordNet in Python?

Last Updated : 22 Oct, 2017
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

WordNet is a large lexical database of English. Nouns, verbs, adjectives and adverbs are grouped into sets of cognitive synonyms (synsets), each expressing a distinct concept. Synsets are interlinked by means of conceptual-semantic and lexical relations.
WordNet’s structure makes it a useful tool for computational linguistics and natural language processing.

WordNet superficially resembles a thesaurus, in that it groups words together based on their meanings. However, there are some important distinctions.

  • First, WordNet interlinks not just word forms—strings of letters—but specific senses of words. As a result, words that are found in close proximity to one another in the network are semantically disambiguated.
  • Second, WordNet labels the semantic relations among words, whereas the groupings of words in a thesaurus does not follow any explicit pattern other than meaning similarity.




# First, you're going to need to import wordnet:
from nltk.corpus import wordnet
  
# Then, we're going to use the term "program" to find synsets like so:
syns = wordnet.synsets("program")
  
# An example of a synset:
print(syns[0].name())
  
# Just the word:
print(syns[0].lemmas()[0].name())
  
# Definition of that first synset:
print(syns[0].definition())
  
# Examples of the word in use in sentences:
print(syns[0].examples())


The output will look like:
plan.n.01
plan
a series of steps to be carried out or goals to be accomplished
[‘they drew up a six-step plan’, ‘they discussed plans for a new bond issue’]

Next, how might we discern synonyms and antonyms to a word? The lemmas will be synonyms, and then you can use .antonyms to find the antonyms to the lemmas. As such, we can populate some lists like:




import nltk
from nltk.corpus import wordnet
synonyms = []
antonyms = []
  
for syn in wordnet.synsets("good"):
    for l in syn.lemmas():
        synonyms.append(l.name())
        if l.antonyms():
            antonyms.append(l.antonyms()[0].name())
  
print(set(synonyms))
print(set(antonyms))


The output will be two sets of synonyms and antonyms
{‘beneficial’, ‘just’, ‘upright’, ‘thoroughly’, ‘in_force’, ‘well’, ‘skilful’, ‘skillful’, ‘sound’, ‘unspoiled’, ‘expert’, ‘proficient’, ‘in_effect’, ‘honorable’, ‘adept’, ‘secure’, ‘commodity’, ‘estimable’, ‘soundly’, ‘right’, ‘respectable’, ‘good’, ‘serious’, ‘ripe’, ‘salutary’, ‘dear’, ‘practiced’, ‘goodness’, ‘safe’, ‘effective’, ‘unspoilt’, ‘dependable’, ‘undecomposed’, ‘honest’, ‘full’, ‘near’, ‘trade_good’} {‘evil’, ‘evilness’, ‘bad’, ‘badness’, ‘ill’}

Now , let’s compare the similarity index of any two words




import nltk
from nltk.corpus import wordnet
# Let's compare the noun of "ship" and "boat:"
  
w1 = wordnet.synset('run.v.01') # v here denotes the tag verb
w2 = wordnet.synset('sprint.v.01')
print(w1.wup_similarity(w2))


Output:
0.857142857143




w1 = wordnet.synset('ship.n.01')
w2 = wordnet.synset('boat.n.01') # n denotes noun
print(w1.wup_similarity(w2))


Output:
0.9090909090909091



Similar Reads

Guide for Non-CS students to get placed in Software companies
This post is especially for people of non-CS branches who have developed interest towards coding and would like to work in a software company. The following post is made keeping in mind the placement process for IIT's but it may be extended to NIT's and other colleges The whole placement process can be divided to three parts: 1. Resume preparation
3 min read
Calendar.get() Method in Java
java.util.Calendar.get() method is a method of java.util.Calendar class. The Calendar class provides some methods for implementing a concrete calendar system outside the package. Some examples of Calendar fields are : YEAR, DATE, MONTH, DAY_OF_WEEK, DAY_OF_YEAR, WEEK_OF_YEAR, MINUTE, SECOND, HOUR, AM_PM, WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, HOUR_OF
3 min read
array get() function in C++ STL
The array::get() is a built-in function in C++ STL which returns a reference to the i-th element of the array container. Syntax: get[Tex][/Tex](array_name) Parameters: The function accepts two mandatory parameters which are described below. i - position of an element in the array, with 0 as the position of the first element. arr_name - an array con
2 min read
How to Get Column from One Table to another in Power Bi
Real-world data is always messy. There will be always in need for adding new columns from one table to another because no table will have complete information. Adding a column allows for more efficient data analysis as well as the ability to add additional information to the table. Adding a column from one table to another helps us to combine data
4 min read
Maximum time required for all patients to get infected
Given a matrix arr[][], consisting of only 0, 1, and 2, that represents an empty ward, an uninfected patient, and an infected patient respectively. In one unit of time, an infected person at index (i, j) can infect an uninfected person adjacent to it i.e., at index (i - 1, j), (i + 1, j), (i, j - 1), and (i, j + 1). The task is to find the minimum
15+ min read
An interesting solution to get all prime numbers smaller than n
This approach is based on Wilson's theorem and uses the fact that factorial computation can be done easily using DP Wilson's theorem says if a number k is prime then ((k-1)! + 1) % k must be 0. Below is a Python implementation of the approach. Note that the solution works in Python because Python supports large integers by default therefore factori
3 min read
Get to know Ubuntu 18.04 LTS | Welcome Bionic Beaver!!
Ubuntu has finally released its new LTS version being 18.04. A short about ubuntu for a newbie ubuntu is linux distribution or basically it is an open source operating system which is product of canonical ltd founded by Mark Shuttlework. In this article we will be basically discussing some cool stuff other installation guide, if you are searching f
4 min read
Shashank Pathak - Geek on the top | Don’t let your mind get diverted to the consequences of not solving a problem
Geek on the top is all about success stories of Geeks who are working hard to chase their goals and are the inspiration for other geeks. Shashank Pathak had an inclination towards reasoning and puzzles since his childhood and hence started Competitive Programming. He is currently doing his Research Internship at IIT Indore. Shashank is one of the c
10 min read
How to get Technical Content Writing Internship at Geeksforgeeks.org?
To all the students who're good at article writing and at the same time knowledgeable enough to write about a particular topic with some good research practices - GeeksforGeeks offers the Technical Content Writing Internship for them. This internship program by GeeksforGeeks is very much recommended to all the students as it'll not help you to expa
5 min read
Do programmers need a Computer Science degree to get a job?
Yea and No!! Let's see how Few years ago, there was a vogue that a college degree was the best way to maximize the likelihood of securing a high-paying job in the field of your choice. But the world has changed, you can easily hear of successful developers who never earned a degree, or college dropouts who made it big in Silicon Valley. If you want
4 min read
How to get rid of Java TLE problem
It happens many times that you have written correct Java code with as much optimization as needed according to the constraints. But, you get TLE ????. This happens due to the time taken by Java to take input and write output using Scanner class which is slow as compared to BufferedReader and StringBuffer class. Read in detail about Scanner Class he
5 min read
Counters in Python | Set 2 (Accessing Counters)
Counters in Python | Set 1 (Initialization and Updation) Counters in Python | Set 2Once initialized, counters are accessed just like dictionaries. Also, it does not raise the KeyValue error (if key is not present) instead the value's count is shown as 0. Example: In this example, we are using Counter to print the key and frequency of that key. The
2 min read
Project Idea | Breakout game in Python
Project Title: Breakout game in Python Introduction: The project 'Breakout game in Python' is proposed to recreate a classical game of Breakout by using the Python language. It is meant to be a fully functional game with scores, lives, game over, and high score management. The high scores can also be uploaded to a website. The game is playable with
2 min read
Numpy.prod() in Python
numpy.prod() returns the product of array elements over a given axis. Syntax: numpy.prod(a, axis=None, dtype=None, out=None, keepdims=) Parameters a : array_like Its the input data. axis : None or int or tuple of ints, its optional It is theAxis or axes along which a product is performed. The default axis is None, it will calculate the product of a
3 min read
SQL using Python and SQLite | Set 2
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web, and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to S
3 min read
Python implementation of automatic Tic Tac Toe game using random number
Tic-tac-toe is a very popular game, so let's implement an automatic Tic-tac-toe game using Python. The game is automatically played by the program and hence, no user input is needed. Still, developing an automatic game will be lots of fun. Let's see how to do this. NumPy and random Python libraries are used to build this game. Instead of asking the
5 min read
Extracting email addresses using regular expressions in Python
Let suppose a situation in which you have to read some specific data like phone numbers, email addresses, dates, a collection of words etc. How can you do this in a very efficient manner?The Best way to do this by Regular Expression. Let take an example in which we have to find out only email from the given input by Regular Expression. Examples: In
3 min read
Monkey Patching in Python (Dynamic Behavior)
In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we can actually change the behavior of code at run-time. # monk.py class A: def func(self): print ("func() is being called") We use above module (monk) in below code and change behavior of func() at run-time by assigning differe
1 min read
Difference between Method and Function in Python
Here, key differences between Method and Function in Python are explained. Java is also an OOP language, but there is no concept of Function in it. But Python has both concept of Method and Function. Python Method Method is called by its name, but it is associated to an object (dependent).A method definition always includes 'self' as its first para
3 min read
Image processing with Scikit-image in Python
scikit-image is an image processing Python package that works with NumPy arrays which is a collection of algorithms for image processing. Let's discuss how to deal with images in set of information and its application in the real world. Important features of scikit-image : Simple and efficient tools for image processing and computer vision techniqu
2 min read
Python | Program to extract frames using OpenCV
OpenCV comes with many powerful video editing functions. In the current scenario, techniques such as image scanning and face recognition can be accomplished using OpenCV. OpenCV library can be used to perform multiple operations on videos. Let’s try to do something interesting using CV2. Take a video as input and break the video into frame by frame
2 min read
Introduction to Convolutions using Python
Convolutions are one of the key features behind Convolutional Neural Networks. For the details of working of CNNs, refer to Introduction to Convolution Neural Network. Feature Learning Feature Engineering or Feature Extraction is the process of extracting useful patterns from input data that will help the prediction model to understand better the r
6 min read
Implementation of Dynamic Array in Python
What is a dynamic array? A dynamic array is similar to an array, but with the difference that its size can be dynamically modified at runtime. Don't need to specify how much large an array beforehand. The elements of an array occupy a contiguous block of memory, and once created, its size cannot be changed. A dynamic array can, once the array is fi
4 min read
Python | Form validation using django
Prerequisites: Django Installation | Introduction to DjangoDjango works on an MVT pattern. So there is a need to create data models (or tables). For every table, a model class is created. Suppose there is a form that takes Username, gender, and text as input from the user, the task is to validate the data and save it.In django this can be done, as
5 min read
sinh() function in C++/python
The sinh() is an inbuilt function in C++/python which returns the hyperbolic sine of an angle given in radians. Syntax : sinh(data_type x)Parameter :The function accepts one mandatory parameter x which specifies the hyperbolic angle in radian. The parameter can be of double, float or long double datatype. Return Value: The function returns the hype
3 min read
Python program to print even length words in a string
Given a string. The task is to print all words with even length in the given string. Examples: Input: s = "This is a python language" Output: This is python language Input: s = "i am laxmi" Output: am Method: Finding even length words using for loop and if statement and without using the def function. First split the given string using the split()
8 min read
Inheritance in Python | Set 2
Prerequisite : basics of inheritance in Python, Inheritance, examples of object, issubclass and super There are 2 built-in functions in Python that are related to inheritance. They are: 1. isinstance(): It checks the type of an object. Its syntax is: isinstance(object_name, class_name) It would return True if the class of object_name is class_name
4 min read
Sum of list (with string types) in Python
In Python, type of behavior will not change for data type. Below example is list containing integer type in string.so, we have to take all int type numbers from list even it is declared in string. Examples: Input : list1 = [12, 'geek', 2, '41', 'for', 10, '8', 6, 4, 'geeks', 7, '10'] Output : 100 Input : list1 = [100, 'geek', 200, '400', 'for', 101
4 min read
Priority Queue in Python
Priority Queues are abstract data structures where each data/value in the queue has a certain priority. For example, In airlines, baggage with the title “Business” or “First-class” arrives earlier than the rest. Priority Queue is an extension of the queue with the following properties. An element with high priority is dequeued before an element wit
2 min read
Python program to copy odd lines of one file to other
Program to read the contents of a file and copy only the content of odd lines into a new file. By identifying whether the line number is odd or even in Python. Examples: Input : Hello World Python Language Output : Hello Python Explanation: The output file has only the odd line form the input fileCopy odd lines of one file to another file in Python
2 min read
Article Tags :
Practice Tags :