SequenceMatcher.ratio, autojunk, and get_close_matches
difflib.SequenceMatcher(isjunk=None, a='', b='', autojunk=True)
SequenceMatcher.ratio()
difflib.get_close_matches(word, possibilities, n=3, cutoff=0.6)ratio() is 2*M/T over matching elements. It is not a semantic difference. autojunk can change that number on long sequences with a popular element.
| Parameter | Description |
|---|---|
isjunk | Optional callable that marks an element as junk, or None for no user-defined junk. |
a, b | The two sequences to compare. Their elements must be hashable. |
autojunk | If True (the default), popular elements in a sufficiently long second sequence are treated as junk. Pass False to disable the heuristic. |
word, possibilities | get_close_matches compares word with each item in possibilities, typically strings. |
n, cutoff | n is the maximum number of matches to return and must be greater than 0. cutoff is a float in [0, 1]; the default is 0.6. |
Returns: ratio() returns a float in [0, 1]. get_close_matches returns a list of the best matches, most similar first.
- The last two prints use two 206-element lists that share six letters and two hundred "x" tokens, but with the popular block on opposite ends. autojunk=True treats "x" as popular junk and the ratio drops sharply; autojunk=False keeps those matches.
- This is not a visual or semantic text-diff test.
from difflib import SequenceMatcher, get_close_matches
print(SequenceMatcher(None, 'car', 'automobile').ratio())
print(SequenceMatcher(None, 'colour', 'color').ratio())
print(SequenceMatcher(None, 'abc', 'abc').ratio())
print(get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']))
a = ['x'] * 200 + list('abcdef')
b = list('abcdef') + ['x'] * 200
print(SequenceMatcher(None, a, b, autojunk=True).ratio())
print(SequenceMatcher(None, a, b, autojunk=False).ratio())Expected output
0.15384615384615385
0.9090909090909091
1.0
['apple', 'ape']
0.02912621359223301
0.970873786407767
Related: Inline text diff tool, Code diff tool, str methods