noben
noben

Reputation: 561

python appending items in a dictionary with for loop

I am writing a nested for loop to judge if two words are similar in pronunciation. My code is like below:

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)

The result should be a dictionary called wordsDict. For example key "university" will have a value "anniversary" since their phoneme are similar (the sm. ratio is 0.66666, which is greater than 0.6), but when the input is "university" and "good", "good" will also be append to a the key "university", but in fact the similarity of "university" and "good" is 0.0, less than 0.6. It seems my "if" control statement fails. How to make the "if" statement work?

Upvotes: 0

Views: 299

Answers (1)

inspectorG4dget
inspectorG4dget

Reputation: 114035

The problem is with the way you're using sm.ratio. sm.ratio is a function. To get the value that you're after, try calling it: 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

Upvotes: 2

Related Questions