如何使用Python在WordNet中生成形容词反义词列表

10

我希望在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的本地语言。


  1. 从nltk.corpus中导入wordnet库。
  2. 对于wordnet字典中的每个形容词adj,获取所有形容词。
  3. 打印adj和反义词,列出每个形容词的所有反义词。
  4. 列表完成后,将其导出到txt文件。
- Sebastian Zeki
由于超/下位词是通过synsets链接的,而反义词是通过lemma链接的,因此在WordNet中列出反义词并不那么简单。 - alvas
2个回答

13
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
...

代码似乎不能工作。我将其修改以消除在pos和lemmas之后的()导致的错误。现在当我使用以下代码时,会出现这个错误:Traceback(最近的调用最后): File“<stdin>”,第5行,在<module>中 Type Error:“str”对象不可调用,我使用以下代码:from nltk.corpus import wordnet as wn for i in wn.all_synsets(): 如果i.pos为['a','s']:对于j in i.lemmas: 如果j.antonyms():则print j.name(),j.antonyms()[0] .name() - Sebastian Zeki
好的,我已经解决了。代码应该是这样的:from nltk.corpus import wordnet as wn for i in wn.all_synsets(): if i.pos in ['a', 's']: for j in i.lemmas: if j.antonyms(): print j.name, j.antonyms()[0].name - Sebastian Zeki
1
请更新您的NLTK,新的NLTK使用获取函数而不是访问synset属性。 - alvas

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"))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接