FuzzyWuzzy and Levenshtein

FuzzyWuzzy

  • 簡單比較
>>> from fuzzywuzzy import fuzz
>>> fuzz.ratio("this is pass","this is a poce!")
67
  • 部分比
>>> fuzz.partial_ratio("this is a text", "this is a test!")
    93
  • 單詞排序比
>>> fuzz.ratio("fuzzy wuzzy was ","wuzzy,fuzzy as dfd")
53
>>> fuzz.token_sort_ratio("fuzzy wuzzy was ","wuzzy,fuzzy as dfd")
67
  • 單詞集合比
>>> fuzz.token_sort_ratio("fuzzy was a ced", "fuzzy fuzzy wer a bear")
    59
>>> fuzz.token_set_ratio("fuzzy was a ced", "fuzzy fuzzy wer a bear")
    71
  • Process
>>> from suzzywuzzy import process
>>> choices = ["Atlanta hello", "New York Jets", "New York Giants", "Dallas bob_dd"]
>>> process.extract("new york jets", choices, limit=2)
    [('New York Jets', 100), ('New York Giants', 79)]
>>> process.extractOne("cowboys", choices)
    ("Dallas Cowboys", 90)

Levenshtein

  • Levenshtein.hamming(str1,str2)

計算漢明距離,要求str1很str2的長度必須一致。是描述兩個等長字串之間對應位置上不同字符的個數

  • Levenshtein.distance(str1,str2)

計算編輯距離(也稱為Levenshtein距離)。是描述由一個字符轉化為另一個字符串最少的操作次數,在其中包括插入、刪除、替換

  def levenshtein(first,second):
      if len(first)>len(second):
          first,second = second,first
  
      if len(first) == 0:
          return len(second)
      if len(second) == 0:
          return len(first)
  
      first_length = len(first)+1
      second_length = len(second)+1
  
      distance_matrix = [range(second_length) for x in range(first_length)]
      print distance_matrix[1][1],distance_matrix[1][2],distance_matrix[1][3],distance_matrix[1][4]
  
      for i in range(1,first_length):
          for j in range(1,second_length):
              deletion = distance_matrix[i-1][j]+1
              insertion = distance_matrix[i][j-1]+1
              substitution = distance_matrix[i-1][j-1]
  
              if first[i-1] != second[j-1]:
                  substitution += 1
  
              distance_matrix[i][j] = min(insertion,deletion,substitution)
  
      print distan_matrix
      return distance_matrix[first_length-1][second_length-1]
  ```
- Levenshtein.ratio(str1,str2)
> 計算萊文斯坦比。計算公式
```math
(sum - idist)/sum

其中sum是指str1和str2的字符串長度總和。idist是類編輯距離
注:這里的類編輯距離不是2中所講的編輯距離,2中三種操作中的每個操作+1,而此處,刪除、插入依然加+1,但是替換加2
這樣做的目的是:ratio('a','c'),sum=2 按2中計算為(2-1)/2=0.5,'a'/'c'沒有重合,顯然不合算,但是替換操作+2,就會解決這個問題

  • Levenshtein.jaro(str1,str2)

計算jaro距離


其中m為s1,s2的匹配長度,當某位置的認為匹配當該位置字符相同,或者不超過



t是調換次數的一般

  • Levenshtein.jaro_winkler(str1,str2)

計算jaro_Winkler距離
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容