如何在 Python 中從 NLTK WordNet 獲取同義詞/反義詞
WordNet 是 Python 的自然語言工具包的一部分。它是一個大型的英語名詞、形容詞、副詞和動詞詞庫。這些詞被分組到一些認知同義詞集中,稱為同義詞集。
要使用 Wordnet,首先我們必須安裝 NLTK 模組,然後下載 WordNet 包。
$ sudo pip3 install nltk $ python3 >>> import nltk >>>nltk.download('wordnet')
在 Wordnet 中,有一些片語,它們的含義相同。
在第一個示例中,我們將看到 Wordnet 如何返回單詞的含義和其他詳細資訊。有時,如果有一些示例可用,它也可能會提供這些示例。
示例程式碼
from nltk.corpus import wordnet #Import wordnet from the NLTK synset = wordnet.synsets("Travel") print('Word and Type : ' + synset[0].name()) print('Synonym of Travel is: ' + synset[0].lemmas()[0].name()) print('The meaning of the word : ' + synset[0].definition()) print('Example of Travel : ' + str(synset[0].examples()))
輸出
$ python3 322a.word_info.py Word and Type : travel.n.01 Synonym of Travel is: travel The meaning of the word : the act of going from one place to another Example of Travel : ['he enjoyed selling but he hated the travel'] $
在前面的示例中,我們獲取了有關某些單詞的詳細資訊。在這裡,我們將看到 Wordnet 如何傳送給定單詞的同義詞和反義詞。
示例程式碼
import nltk from nltk.corpus import wordnet #Import wordnet from the NLTK syn = list() ant = list() for synset in wordnet.synsets("Worse"): for lemma in synset.lemmas(): syn.append(lemma.name()) #add the synonyms if lemma.antonyms(): #When antonyms are available, add them into the list ant.append(lemma.antonyms()[0].name()) print('Synonyms: ' + str(syn)) print('Antonyms: ' + str(ant))
輸出
$ python3 322b.syn_ant.py Synonyms: ['worse', 'worse', 'worse', 'worsened', 'bad', 'bad', 'big', 'bad', 'tough', 'bad', 'spoiled', 'spoilt', 'regretful', 'sorry', 'bad', 'bad', 'uncollectible', 'bad', 'bad', 'bad', 'risky', 'high-risk', 'speculative', 'bad', 'unfit', 'unsound', 'bad', 'bad', 'bad', 'forged', 'bad', 'defective', 'worse'] Antonyms: ['better', 'better', 'good', 'unregretful'] $
NLTK Wordnet 還有另一個很棒的功能,透過使用它,我們可以檢查兩個單詞是否近似相等。它將返回一對單詞的相似度比率。
示例程式碼
import nltk from nltk.corpus import wordnet #Import wordnet from the NLTK first_word = wordnet.synset("Travel.v.01") second_word = wordnet.synset("Walk.v.01") print('Similarity: ' + str(first_word.wup_similarity(second_word))) first_word = wordnet.synset("Good.n.01") second_word = wordnet.synset("zebra.n.01") print('Similarity: ' + str(first_word.wup_similarity(second_word)))
輸出
$ python3 322c.compare.py Similarity: 0.6666666666666666 Similarity: 0.09090909090909091 $
廣告