如何比较两个字符串并找出相似度百分比?

How to compare two strings and find the percent of similarity?

如何比较两个字符串并打印相似度百分比。找到字符串之间的相似性很容易,但很难以百分比显示它。 如何在Ruby中实现?

解决这个问题的一种方法是从 Levenshtein 距离出发,它会告诉您将一个字符串转换为另一个字符串需要多少次操作。

在 Ruby 中,有一个 gem 可以用于此,称为 Levenshtein

要将需要的操作次数换算成百分比,可以出100%就是要从头一路写字串,没有相似之处。那将是最长字符串的长度。另一种选择是使用字符串的平均长度,但在这个例子中,我将使用最长的。

这是一种使用 levenshtein gem 并获取它们的接近程度的百分比的方法:

require 'levenshtein'
def distance_percent(first,second)
    max_distance = [first,second].max_by(&:length).length
    distance = Levenshtein.distance(first,second)
    (100.0 / max_distance * distance).round.to_s + "%"
end

以下是该方法对不同字符串 return 的一些示例。

string_one = "1234567890"
string_two = "1234567890"
puts distance_percent(string_one, string_two)

# => 0%

这个returns 0%因为他们之间的距离是0.

string_one = "1234512345"
string_two = "6789067890"
puts distance_percent(string_one, string_two)

# => 100%

这将 return 100% 因为有 none 个相同的字符。

string_one = "This is a string"
string_two = "This is another string"
puts distance_percent(string_one, string_two)

# => 27%

这将 return 27% 因为 27% 的字符串彼此不同。