美文网首页程序员
FuzzyWuzzy and Levenshtein

FuzzyWuzzy and Levenshtein

作者: 羽恒 | 来源:发表于2017-07-17 00:09 被阅读278次

    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距离

    相关文章

      网友评论

        本文标题:FuzzyWuzzy and Levenshtein

        本文链接:https://www.haomeiwen.com/subject/tznxkxtx.html