如何用Python从WordNet生成形容词的反义词列表

11 投票
2 回答
10009 浏览
提问于 2025-04-18 09:36

我想在Python中做以下事情(我有NLTK这个库,但我对Python不太熟悉,所以写了以下奇怪的伪代码):

from nltk.corpus import wordnet as wn  #Import the WordNet library
for each adjective as adj in wn        #Get all adjectives from the wordnet dictionary
    print adj & antonym                #List all antonyms for each adjective 
once list is complete then export to txt file

这样我就可以生成一个完整的形容词反义词字典。我觉得这个应该可以实现,但我不知道怎么写Python脚本。我想用Python来做,因为NLTK就是用这个语言写的。

2 个回答

1

下面这个函数使用WordNet来返回一个给定单词的形容词反义词集合:

from nltk.corpus import wordnet as wn

def antonyms_for(word):
    antonyms = set()
    for ss in wn.synsets(word):
        for lemma in ss.lemmas():
            any_pos_antonyms = [ antonym.name() for antonym in lemma.antonyms() ]
            for antonym in any_pos_antonyms:
                antonym_synsets = wn.synsets(antonym)
                if wn.ADJ not in [ ss.pos() for ss in antonym_synsets ]:
                    continue
                antonyms.add(antonym)
    return antonyms

使用方法:

print(antonyms_for("good"))
14
from nltk.corpus import wordnet as wn

for i in wn.all_synsets():
    if i.pos() in ['a', 's']: # If synset is adj or satelite-adj.
        for j in i.lemmas(): # Iterating through lemmas for each synset.
            if j.antonyms(): # If adj has antonym.
                # Prints the adj-antonym pair.
                print j.name(), j.antonyms()[0].name()

请注意,这里会有反向重复的情况。

[输出]:

able unable
unable able
abaxial adaxial
adaxial abaxial
acroscopic basiscopic
basiscopic acroscopic
abducent adducent
adducent abducent
nascent dying
dying nascent
abridged unabridged
unabridged abridged
absolute relative
relative absolute
absorbent nonabsorbent
nonabsorbent absorbent
adsorbent nonadsorbent
nonadsorbent adsorbent
absorbable adsorbable
adsorbable absorbable
abstemious gluttonous
gluttonous abstemious
abstract concrete
...

撰写回答