Synonyms and Antonyms
To find synonyms of a word, lemma can be used. This example is to find synonyms of "cookbook".
>>> syn = wordnet.synsets('cookbook')[0] >>> lemmas = syn.lemmas >>> len(lemmas) 2 >>> lemmas [Lemma('cookbook.n.01.cookbook'), Lemma('cookbook.n.01.cookery_book')] >>> lemmas[0].name 'cookbook' >>> lemmas[1].name 'cookery_book' >>> lemmas[0].synset == lemmas[1].synset True
As long as seeing this, 'cookbook" and "cookery_book" are put into one synset "cookbook" as lemmas. This logic is to show name of lemmas.
>>> lemmas[1].synset Synset('cookbook.n.01') >>> [lemma.name for lemma in syn.lemmas] ['cookbook', 'cookery_book']
This is another example to find synonyms of a word 'book'.
>>> synonyms = [] >>> for syn in wordnet.synsets('book'): ... for lemma in syn.lemmas: ... synonyms.append(lemma.name) ... >>> len(synonyms) 38
Initialize a variable synonyms then get lemmas of synsets('book'). As a result, there are 38 elements in synonyms. To get entire list of synonyms:
>>> synonyms ['book', 'book', 'volume', 'record', 'record_book', 'book', 'script', 'book', 'p layscript', 'ledger', 'leger', 'account_book', 'book_of_account', 'book', 'book' , 'book', 'rule_book', 'Koran', 'Quran', "al-Qur'an", 'Book', 'Bible', 'Christia n_Bible', 'Book', 'Good_Book', 'Holy_Scripture', 'Holy_Writ', 'Scripture', 'Word _of_God', 'Word', 'book', 'book', 'book', 'reserve', 'hold', 'book', 'book', 'bo ok']
It looks some words are duplicated, for example, there are more than 10 'Book' or 'book'. by adding set, get distinct values.
>>> len(set(synonyms)) 25 >>> set(synonyms) set(['record_book', 'Holy_Writ', 'Book', 'Good_Book', 'Scripture', 'script', 'Qu ran', 'ledger', 'book', 'book_of_account', 'Christian_Bible', 'Bible', 'Word', ' leger', 'Koran', 'playscript', 'hold', 'Word_of_God', 'volume', 'rule_book', 'ac count_book', 'Holy_Scripture', 'record', "al-Qur'an", 'reserve'])
The number is reduced to 25 and no duplication.
Then try to get antonyms.
>>> gn2 = wordnet.synset('good.n.02') >>> gn2.definition 'moral excellence or admirableness' >>> evil = gn2.lemmas[0].antonyms()[0] >>> evil.name 'evil' >>> evil.synset.definition 'the quality of being morally wrong in principle or practice'
By using antonyms(), can get antonyms can be displayed. This is another example and easy to understand for non-Enlglish speaking guys like me.
>>> ga1 = wordnet.synset('good.a.01') >>> ga1.definition 'having desirable or positive qualities especially those suitable for a thing sp ecified' >>> bad = ga1.lemmas[0].antonyms()[0] >>> bad.name 'bad' >>> bad.synset.definition 'having undesirable or negative qualities' >>>