How to use SequenceMatcher to find similarity between two strings?

joolie picture joolie · Jan 26, 2011 · Viewed 51k times · Source
import difflib

a='abcd'
b='ab123'
seq=difflib.SequenceMatcher(a=a.lower(),b=b.lower())
seq=difflib.SequenceMatcher(a,b)
d=seq.ratio()*100
print d

I used the above code but obtained output is 0.0. How can I get a valid answer?

Answer

Lennart Regebro picture Lennart Regebro · Jan 26, 2011

You forgot the first parameter to SequenceMatcher.

>>> import difflib
>>> 
>>> a='abcd'
>>> b='ab123'
>>> seq=difflib.SequenceMatcher(None, a,b)
>>> d=seq.ratio()*100
>>> print d
44.4444444444

http://docs.python.org/library/difflib.html