12.2.12 Getting Definitions, Synonyms and Antonyms from WordNet

Getting Definitions

In [1]:
from textblob import Word
In [2]:
happy = Word('happy')
  • Word class’s definitions property returns a list of all the word’s definitions in the WordNet database
In [3]:
happy.definitions
Out[3]:
['enjoying or showing or marked by joy or pleasure',
 'marked by good fortune',
 'eagerly disposed to act or to be of service',
 'well expressed and to the point']
  • Database does not necessarily contain every dictionary definition
  • define method that enables you to pass a part of speech as an argument so you can get definitions matching only that part of speech

Getting Synonyms

  • synsets are sets of synonyms
In [4]:
happy.synsets
Out[4]:
[Synset('happy.a.01'),
 Synset('felicitous.s.02'),
 Synset('glad.s.02'),
 Synset('happy.s.04')]
  • Synset — a group of synonyms
  • happy.a.01:
    • happy is the original Word’s lemmatized form
    • a is the part of speecha for adjective, n for noun, v for verb, r for adverb or s for adjective satellite.
      • Many adjective synsets have satellite synsets representing similar adjectives
    • 01 is the index number of the corresponding meaning in the WordNet database
  • Method get_synsets enables you to pass a part of speech to can get Synsets for that part of speech
  • Each Synset has a lemmas method that returns a list of Lemma objects representing the synonyms
  • A Lemma’s name method returns the synonymous word as a string
In [5]:
synonyms = set()
In [6]:
for synset in happy.synsets:
    for lemma in synset.lemmas():
        synonyms.add(lemma.name())
In [7]:
synonyms
Out[7]:
{'felicitous', 'glad', 'happy', 'well-chosen'}

Getting Antonyms

  • If the word represented by a Lemma has antonyms in the WordNet database, invoking the Lemma’s antonyms method returns a list of Lemmas representing the antonyms
In [8]:
lemmas = happy.synsets[0].lemmas()
In [9]:
lemmas
Out[9]:
[Lemma('happy.a.01.happy')]
  • Check whether the database has any corresponding antonyms for that Lemma
In [10]:
lemmas[0].antonyms()
Out[10]:
[Lemma('unhappy.a.01.unhappy')]

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.