python在字典中用for循环附加项

2024-10-03 13:17:55 发布

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

我正在写一个嵌套的for循环来判断两个单词的发音是否相似。我的代码如下:

wordsDict = nltk.defaultdict(list)
for s1 in prondict[word1]:
    for s2 in prondict[word2]:
        sm=difflib.SequenceMatcher(None, s1, s2)
            if (sm.ratio != 1 and sm.ratio >= 0.6):
                #push word2 into the dict with key word1
                wordsDict[word1].append(word2)

结果应该是一本名为wordsDict的词典。例如,关键字“university”将有一个值“announdary”,因为它们的音素相似(sm)。比值为0.66666,大于0.6),但当输入为“大学”和“好”时,“好”也会附加到关键字“大学”后面,但实际上“大学”和“好”的相似度是0.0,小于0.6。我的“如果”控制语句似乎失败了。如何使“如果”语句起作用?在


Tags: infor关键字语句单词大学sm发音
1条回答
网友
1楼 · 发布于 2024-10-03 13:17:55

问题在于你使用sm.ratio的方式。sm.ratio是一个函数。若要获取所需的值,请尝试调用它:sm.ratio()

In [77]: sm = difflib.SequenceMatcher(None, "university", "anniversary")

In [78]: sm.ratio
Out[78]: <bound method SequenceMatcher.ratio of <difflib.SequenceMatcher instance at 0x104d00488>>

In [79]: sm.ratio()
Out[79]: 0.6666666666666666

相关问题 更多 >