def string_similarity(string1, string2):
 vocabulary = set(list((string1 + string2)))
 vec1 = [string1.count(v) for v in vocabulary]
 vec2 = [string2.count(v) for v in vocabulary]
 try:
  return (float(sum(((vec1[i] * vec2[i]) for i in range(len(vocabulary))))) / (math.sqrt(sum(((v1 ** 2) for v1 in vec1))) * math.sqrt(sum(((v2 ** 2) for v2 in vec2)))))
 except ZeroDivisionError:
  return 0

def string_similarity ( string1 , string2 ) : vocabulary = set ( list ( ( string1 + string2 ) ) ) vec1 = [ string1 . count ( v ) for v in vocabulary ] vec2 = [ string2 . count ( v ) for v in vocabulary ] try : return ( float ( sum ( ( ( vec1 [ i ] * vec2 [ i ] ) for i in range ( len ( vocabulary ) ) ) ) ) / ( math . sqrt ( sum ( ( ( v1 ** 2 ) for v1 in vec1 ) ) ) * math . sqrt ( sum ( ( ( v2 ** 2 ) for v2 in vec2 ) ) ) ) ) except ZeroDivisionError : return 0
this implements a "cosine-similarity" algorithm as described for example in *proceedings of the 22nd international conference on computation linguistics* .