Python Practice › String Programs › Program 82

Similarity of two strings

MediumString Programs · 82 of 106

Write a Python program to measure how similar two strings are.

Advertisement
Input
"Learning is fun in Sqatools", "Sqatools Online Learning Platform"
Output
Similarity: 0.4
Word overlap (Jaccard): 0.29

Approach

  1. difflib.SequenceMatcher returns a ratio from 0 (different) to 1 (identical).

Solution

Python
from difflib import SequenceMatcher s1 = "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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs