1

我的循环有问题。如果该意义的任何引理与 word2 匹配,我需要它只打印一次“同义词”,否则“不是同义词”,但只打印一次。

from nltk.corpus import wordnet as wn

word1 = 'motorcar'
word2 = 'automobile'

for syn in wn.synsets(word1):
    for lemma in syn.lemma_names():
        if lemma == word2 and lemma != word1:
            print('Synonyms')
        elif all(syn.lemma_names()) != word2:
            print('not synonyms')
4

3 回答 3

0

我是 Python 包wordhoard的作者。该包可用于查找单词之间的语义关系,包括单词的同义词、同义词、上位词、下位词和同音词。

from wordhoard import Synonyms

word1 = 'motorcar'
word2 = 'automobile'

synonym_list = Synonyms(word1).find_synonyms()
find_word = [word for word in synonym_list if word == word2]

if find_word is not None:
    print(f'{word2} is a synonym of {word1}')
    # print output
    automobile is a synonym of motorcar.
else:
    print(f'{word2} is not a synonym of {word1}')

我发现wordnet非常有限。例如,这些是wordnet中motorcar的同义词:

['auto', 'automobile', 'car', 'machine']

Wordhoard旨在查询其他来源。例如,下面的查询返回单词motorcar的 152 个同义词。

from wordhoard import Synonyms

synonym_list = Synonyms('motorcar').find_synonyms()
print(len(synonym_list))
152

如果您决定使用wordhoard ,请告诉我它如何适用于您的用例。

于 2020-12-08T13:17:22.763 回答
0

结果相同,但将所有引理列表合并到一个名为“名称”的列表中,而不是使用枢轴布尔值:

from nltk.corpus import wordnet as wn

word1 = 'motorcar'
word2 = 'automobile'

names = []
for syn in wn.synsets(word1):
    for lemma in syn.lemma_names():
        names.append(lemma)

print('Synonyms' if word2 in names else 'not synonyms')
于 2020-12-07T13:13:30.953 回答
0

通常的模式是在循环外初始化一个变量,然后在循环结束时报告结果。像这样的东西:

from nltk.corpus import wordnet as wn

word1 = 'motorcar'
word2 = 'automobile'

for syn in wn.synsets(word1):
    is_synonym = False
    for lemma in syn.lemma_names():
        if lemma == word2 and lemma != word1:
            is_synonym = True
    print('Synonyms' if is_synonym else 'not synonyms')
于 2020-12-07T10:22:14.000 回答