From Calculate Levenshtein distance between two strings in Python it is possible to calculate distance and similarity between two given strings(sentences).
And from Levenshtein Distance and Text Similarity in Python to return the matrix for each character and distance for two strings.
Are there any ways to calculate distance and similarity between each word in a string and print the matrix for each word in a string(sentences)?
a = "This is a dog."
b = "This is a cat."
from difflib import ndiff
def levenshtein(seq1, seq2):
size_x = len(seq1) + 1
size_y = len(seq2) + 1
matrix = np.zeros ((size_x, size_y))
for x in range(size_x):
matrix [x, 0] = x
for y in range(size_y):
matrix [0, y] = y
for x in range(1, size_x):
for y in range(1, size_y):
if seq1[x-1] == seq2[y-1]:
matrix [x,y] = min(
matrix[x-1, y] + 1,
matrix[x-1, y-1],
matrix[x, y-1] + 1
)
else:
matrix [x,y] = min(
matrix[x-1,y] + 1,
matrix[x-1,y-1] + 1,
matrix[x,y-1] + 1
)
print (matrix)
return (matrix[size_x - 1, size_y - 1])
levenshtein(a, b)
Outputs
>> 3
Matrix
[[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.]
[ 1. 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13.]
[ 2. 1. 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.]
[ 3. 2. 1. 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.]
[ 4. 3. 2. 1. 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
[ 5. 4. 3. 2. 1. 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
[ 6. 5. 4. 3. 2. 1. 0. 1. 2. 3. 4. 5. 6. 7. 8.]
[ 7. 6. 5. 4. 3. 2. 1. 0. 1. 2. 3. 4. 5. 6. 7.]
[ 8. 7. 6. 5. 4. 3. 2. 1. 0. 1. 2. 3. 4. 5. 6.]
[ 9. 8. 7. 6. 5. 4. 3. 2. 1. 0. 1. 2. 3. 4. 5.]
[10. 9. 8. 7. 6. 5. 4. 3. 2. 1. 0. 1. 2. 3. 4.]
[11. 10. 9. 8. 7. 6. 5. 4. 3. 2. 1. 1. 2. 3. 4.]
[12. 11. 10. 9. 8. 7. 6. 5. 4. 3. 2. 2. 2. 3. 4.]
[13. 12. 11. 10. 9. 8. 7. 6. 5. 4. 3. 3. 3. 3. 4.]
[14. 13. 12. 11. 10. 9. 8. 7. 6. 5. 4. 4. 4. 4. 3.]]
General Levenshtein distance for character level shown in below fig.
Is it possible to calculate Levenshtein Distance for Word Level?
Required Matrix
This is a cat
This
is
a
dog
NLTK
library has Levenshtein function. take a look nltk.org/howto/metrics.html . Please elaborate if you are looking for a more precise answer $\endgroup$