Use Shingle (n-gram) based algorithms
masterShingle-based algorithms convert strings into sets of n-grams (sequences of $n$ characters). You can use them in two ways:
- Directly: Compute distance between two strings using
QGram. - For large datasets: Pre-compute string profiles using
get_profile()and then compare profiles usingsimilarity_profiles().
CRITICAL: You must use the same KShingling object (the same $n$ value) to parse all input strings for profile comparison to work.
# Direct distance
from strsimpy.qgram import QGram
qgram = QGram(2)
print(qgram.distance('ABCD', 'ABCE'))
# Profile comparison for large datasets
from strsimpy.cosine import Cosine
cosine = Cosine(2)
s0 = 'My first string'
s1 = 'My other string...'
p0 = cosine.get_profile(s0)
p1 = cosine.get_profile(s1)
print(cosine.similarity_profiles(p0, p1))