如何检查单词是否在synset中?

2024-09-23 22:18:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着比较两个单词列表来检查:

  1. word1 list包含单词2 list的synsets中的单词

  2. word2 list由单词1 list的synsets中的单词组成

如果单词在语法集中,则返回True

以下是我的代码:

from nltk.corpus import wordnet as wn

word1 =  ['study', 'car']
word2 =  ['learn', 'motor']

def getSynonyms(word1):
    synonymList1 = []
    for data1 in word1:
        wordnetSynset1 = wn.synsets(data1)
        tempList1=[]
        for synset1 in wordnetSynset1:
            synLemmas = synset1.lemma_names()
            for i in xrange(len(synLemmas)):
                word = synLemmas[i].replace('_',' ')
                if word not in tempList1:
                    tempList1.append(word)
        synonymList1.append(tempList1)
    return synonymList1


def checkSynonyms(word1, word2):
    for i in xrange(len(word1)):
        for j in xrange(len(word2)):
            d1 = getSynonyms(word1)
            d2 = getSynonyms(word2)
            if word1[i] in d2:
                return True
            elif word2[j] in d1:
                return True
            else:
                return False

print word1
print
print word2
print
print getSynonyms(word1)
print
print getSynonyms(word2)
print 
print checkSynonyms(word1, word2)
print

但输出如下:

^{pr2}$

我们可以看到,word1中的单词'study'也存在于word2>;u'study'的语法集中

为什么返回false?在


Tags: intrueforreturn单词listprintstudy
1条回答
网友
1楼 · 发布于 2024-09-23 22:18:35

由于要比较word1和d2的字符串值,请不要使用if word1[i] in d2:,因为它将比较word1的字符串值与d2的数组值,例如它将比较:

'study' == [u'survey', u'study', u'work', u'report', u'written report', u'discipline', 
u'subject', u'subject area', u'subject field', u'field', u'field of study', 
u'bailiwick', u'sketch', u'cogitation', u'analyze', u'analyse', u'examine', 
u'canvass', u'canvas', u'consider', u'learn', u'read', u'take', u'hit the 
books', u'meditate', u'contemplate']

它将绝对返回False。在

所以,不要使用if word1[i] in d2:,而应该使用if word1[i] in d2[k]:,其中{}是迭代器。在

希望对你有帮助。在

相关问题 更多 >