similarity of string in python sentence code example
Example 1: check string similarity python
from difflib import SequenceMatcher
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
>>> similar("Apple","Appel")
0.8
>>> similar("Apple","Mango")
0.0
Example 2: sentence similarity python
from sentence_transformers import SentenceTransformer
from sentence_transformers.util import pytorch_cos_sim
model = SentenceTransformer('stsb-roberta-large')
sentences = list(...)
embeddings = bert_model.encode(sentences)
cos_similarity = pytorch_cos_sim(embeddings[0], embeddings[1])