我试着比较两个单词列表来检查:
word1 list包含单词2 list的synsets中的单词
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?在
由于要比较word1和d2的字符串值,请不要使用
if word1[i] in d2:
,因为它将比较word1的字符串值与d2的数组值,例如它将比较:它将绝对返回
False
。在所以,不要使用}是迭代器。在
if word1[i] in d2:
,而应该使用if word1[i] in d2[k]:
,其中{希望对你有帮助。在
相关问题 更多 >
编程相关推荐