damerau.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (c) 2018 luozhouyang
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in all
  11. # copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. # SOFTWARE.
  20. import numpy as np
  21. from .string_distance import MetricStringDistance
  22. class Damerau(MetricStringDistance):
  23. def distance(self, s0, s1):
  24. if s0 is None:
  25. raise TypeError("Argument s0 is NoneType.")
  26. if s1 is None:
  27. raise TypeError("Argument s1 is NoneType.")
  28. if s0 == s1:
  29. return 0.0
  30. inf = int(len(s0) + len(s1))
  31. da = dict()
  32. for i in range(len(s0)):
  33. da[s0[i]] = str(0)
  34. for i in range(len(s1)):
  35. da[s1[i]] = str(0)
  36. h = np.zeros((len(s0) + 2, len(s1) + 2))
  37. for i in range(len(s0) + 1):
  38. h[i + 1][0] = inf
  39. h[i + 1][1] = i
  40. for j in range(len(s1) + 1):
  41. h[0][j + 1] = inf
  42. h[1][j + 1] = j
  43. for i in range(1, len(s0) + 1):
  44. db = 0
  45. for j in range(1, len(s1) + 1):
  46. i1 = int(da[s1[j - 1]])
  47. j1 = db
  48. cost = 1
  49. if s0[i - 1] == s1[j - 1]:
  50. cost = 0
  51. db = j
  52. h[i + 1][j + 1] = min(h[i][j] + cost,
  53. h[i + 1][j] + 1,
  54. h[i][j + 1] + 1,
  55. h[i1][j1] + (i - i1 - 1) + 1 + (j - j1 - 1))
  56. da[s0[i - 1]] = str(i)
  57. return h[len(s0) + 1][len(s1) + 1]