Write a Python program to measure how similar two strings are.
Input
"Learning is fun in Sqatools", "Sqatools Online Learning Platform"
Output
Similarity: 0.4
Word overlap (Jaccard): 0.29
Approach
difflib.SequenceMatcher returns a ratio from 0 (different) to 1 (identical).
Solution
Python
fromdifflibimportSequenceMatchers1="Learning is fun in Sqatools"s2="Sqatools Online Learning Platform"ratio=SequenceMatcher(None,s1,s2).ratio()print("Similarity:",round(ratio,2))w1,w2=set(s1.lower().split()),set(s2.lower().split())print("Word overlap (Jaccard):",round(len(w1&w2)/len(w1|w2),2))
Output
Similarity: 0.4
Word overlap (Jaccard): 0.29
Line by line
Line 5
The ratio compares matching blocks of characters.
Lines 8-9
A second measure compares shared words over all distinct words.
Note
Different similarity measures give different numbers, so state which one you use.
Learn the concept
New to this topic? Read the lesson, then come back.