尽管没有相同的语法集,为什么tmp仍然打印1?

2024-09-24 00:32:07 发布

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

我有两个列表要比较:

word1 =  ['orange']
word2 =  ['woman']

然后我用这个函数为列表中的每个单词找到一个语法集:

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

ds1 = getSynonyms([word1[0]])
ds2 = getSynonyms([word2[0]])
newds1 = ",".join(repr(e) for e in ds1)
newds2 = ",".join(repr(e) for e in ds2)

print newds1
print newds2

这是输出:

[u'orange', u'orangeness', u'orange tree', u'Orange', u'Orange River', u'orangish']
[u'woman', u'adult female', u'charwoman', u'char', u'cleaning woman', u'cleaning lady', u'womanhood', u'fair sex']

然后我有另一个功能。此函数检查word1word2之间是否存在类似的语法集。如果找到一个相似的单词,那么函数将返回1,这意味着找到了它:

def cekSynonyms(word1, word2):
    tmp = 0
    ds1 = getSynonyms([word1[0]])
    ds2 = getSynonyms([word2[0]])
    newds1 = ",".join(repr(e) for e in ds1)
    newds2 = ",".join(repr(e) for e in ds2)

    for i in newds1:
        for j in newds2:
            if i == j:
                tmp = 1
            else:
                tmp = 0
    return tmp

print cekSynonyms(word1, word2)

但是输出是1

word1word2之间似乎没有类似的语法集。但是为什么它仍然是1而不是0


Tags: infortmpwordjoinappendreprword1
1条回答
网友
1楼 · 发布于 2024-09-24 00:32:07

循环总是检查完整的列表,并在每次迭代中覆盖tmp。所以列表中最后的元素决定返回值。也许你应该停止这样的检查

for i in newds1:
    for j in newds2:
        if i == j:
            tmp = 1
            print(i, j) #this will tell you why 1 is returned
            return tmp # <<<< return from function 
        else:
            tmp = 0
return tmp

相关问题 更多 >