Skip to main content
 首页 » 编程设计

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

2025年05月04日21itcoder

我有两个字符串说:

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

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

我写下一个简单的代码:

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

此代码告诉我们两个长度相同的字符串之间的“per_deff”,如果它们的长度不同怎么办。我该如何解决我的问题。

请您参考如下方法:

你想要的东西类似于Levenshtein Distance。即使它们的长度不相等,它也会为您提供两个字符串之间的距离。

如果两个字符串完全相同,则距离为 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); 
}