WordNet is a dictionary for programs: words are grouped into sets of synonyms (synsets) with definitions, and linked to antonyms and broader or narrower words.
from nltk.corpus import wordnet
syn = wordnet.synsets("book")
print(syn[0].definition()) # a written work or composition that has been published (printed on pages bound together)
print(syn[0].name()) # book.n.01Synonyms
from nltk.corpus import wordnet
synonyms = []
for s in wordnet.synsets("happy"):
for lemma in s.lemmas():
synonyms.append(lemma.name())
print(sorted(set(synonyms))) # ['felicitous', 'glad', 'happy', 'well-chosen']Antonyms
from nltk.corpus import wordnet
antonyms = {a.name() for s in wordnet.synsets("healthy") for l in s.lemmas() for a in l.antonyms()}
print(sorted(antonyms)) # ['unhealthy']| Call | Gives |
|---|---|
wordnet.synsets(word) | Every sense of the word |
synset.definition() / .examples() | Its meaning / example sentences |
synset.lemmas() | The words in that sense (synonyms) |
lemma.antonyms() | Opposites |
synset.hypernyms() | Broader terms (dog → canine) |