有没有办法定量比较两个字符串的相似性

时间:2016-02-23 07:37:41

标签: python string

我有两个字符串说:

s_1 = "This is a bat"
s_2 = "This is a bag"

以定性方式它们可能相似(1)或不相似(0),在上述情况下它们由于“g”而不相似,而在定量方式中我可以看到一定程度的不相似性在那我怎么能使用python计算从s_1到s_2的后一个“g”的这种不相似性。

我写了一个简单的代码:

Per_deff = float(((Number_of_mutated_sites)/len(s_1))*100)

此代码告诉我们两个相同长度的字符串之间的“per_deff”,如果它们的长度不相同则会怎样。我怎样才能解决我的问题。

4 个答案:

答案 0 :(得分:5)

你想要的东西类似于 Levenshtein距离。即使它们的长度不相等,它也能给出两根弦之间的距离。

如果两个字符串完全相同,则距离将为0,如果它们相似则距离将更小。

来自Wikipedia的示例代码:

// len_s and len_t are the number of characters in string s and t respectively
int LevenshteinDistance(string s, int len_s, string t, int len_t)
{ int cost;

  /* base case: empty strings */
  if (len_s == 0) return len_t;
  if (len_t == 0) return len_s;

  /* test if last characters of the strings match */
  if (s[len_s-1] == t[len_t-1])
      cost = 0;
  else
      cost = 1;

  /* return minimum of delete char from s, delete char from t, and delete char from both */
  return minimum(LevenshteinDistance(s, len_s - 1, t, len_t    ) + 1,
                 LevenshteinDistance(s, len_s    , t, len_t - 1) + 1,
                 LevenshteinDistance(s, len_s - 1, t, len_t - 1) + cost);
}

答案 1 :(得分:1)

您可以使用标准python库difflib

from difflib import SequenceMatcher


s_1 = "This is a bat"
s_2 = "This is a bag"
matcher = SequenceMatcher()
matcher.set_seqs(s_1, s_2)
print matcher.ratio()

答案 2 :(得分:0)

您正在寻找的是编辑距离。

https://pypi.python.org/pypi/editdistance

编辑距离是需要对一个字符串进行编辑以使其成为另一个字符串的编辑次数。

此处也有快速实施:

https://stackoverflow.com/a/24172422/4044442

答案 3 :(得分:0)

如果我理解正确,你想做模糊字符串匹配。存在多个Python库,其中一个是fuzzywuzzy

from fuzzywuzzy import fuzz
s_1 = "This is a bat"
s_2 = "This is a bag"
fuzz.ratio(s_1, s_2)  # returns 92
fuzz.ratio(s_1, s_1)  # returns 100 (max score)
相关问题