我正在编写一个嵌套的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的字典。例如,关键“大学”将具有值“周年纪念”,因为他们的音素相似(sm。比率为0.66666,大于0.6),但是当输入是“大学”和“好”时,“好”将也可以附加到关键的“大学”,但实际上“大学”和“好”的相似度是0.0,小于0.6。似乎我的“if”控制语句失败了。如何使“if”语句有效?
答案 0 :(得分:2)
问题在于您使用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