Python Calculate the Similarity of Two Sentences – Python Tutorial

By | September 14, 2019

Calculating the similarity of two sentences is very useful to nlp, however, to get better similarity result, many researchers use deep learning to improve the process. In this tutorial, we will use python difflib library to calculate, which is very simple to beginners.

python calculate the similarity of two strings

Import library

import difflib

Create a function to calculate the similarity

def string_similar(s1, s2):
    return difflib.SequenceMatcher(None, s1, s2).quick_ratio()

Create two sentences

s1 = 'i love this book'
s2 = 'this book is my favorite'

Calculate the similarity of these two sentences

print (string_similar(s1, s2))

The similarity of these two sentences is: 0.75.

Leave a Reply

Your email address will not be published. Required fields are marked *