簡體   English   中英

有什么方法可以定量比較兩個字符串的相似性

[英]Is there any way to compare two string similarity quantitatively

我有兩個字符串說:

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”,如果它們的長度不相同該怎么辦。 我該如何解決我的問題。

您想要的東西與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);
}

您可以使用標准的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()

您正在尋找的被稱為編輯距離。

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

編輯距離是指對一個字符串進行編入另一字符串所需的編輯次數。

這里也有快速的實現:

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

如果我對您的理解正確,則希望進行模糊字符串匹配。 為此,存在多個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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM