2016-09-27 13 views
1

私はかなり新しいPythonです。私はファジー一致のために曖昧な曖昧さを使用しようとしています。私はpartial_ratio関数を使ってマッチのスコアが間違っていると思います。ここに私の探索のコードは次のとおりです。曖昧な曖昧な部分スコアの取得partial_ratio

>>>from fuzzywuzzy import fuzz 
>>>fuzz.partial_ratio('Subject: Dalki Manganese Ore Mine of M/S Bharat Process and Mechanical Engineers Ltd., Villages Dalki, Soyabahal, Sading and Thakurani R.F., Tehsil Barbil, Distt, Keonjhar, Orissa environmental clearance','Barbil') 
50 

私は、これは100のスコアを返すべきであると信じて、2番目の文字列、「Barbil」以来、最初の文字列に含まれています。私は最後または最初の文字列の先頭に数文字を離陸しようとしたとき、私は100

>>>fuzz.partial_ratio('Subject: Dalki Manganese Ore Mine of M/S Bharat Process and Mechanical Engineers Ltd., Villages Dalki, Soyabahal, Sading and Thakurani R.F., Tehsil Barbil, Distt, Keonjhar, Orissa environmental clear','Barbil') 
100 
>>> fuzz.partial_ratio('ect: Dalki Manganese Ore Mine of M/S Bharat Process and Mechanical Engineers Ltd., Villages Dalki, Soyabahal, Sading and Thakurani R.F., Tehsil Barbil, Distt, Keonjhar, Orissa environmental clearance','Orissa') 
100 

のマッチングスコアを取得することは、100ときの長さのスコアに50のスコアから切り替えるように見えます最初の文字列の199に行く。誰が起こっている可能性についての洞察力を持っていますか?

答えて

0

文字列のいずれかが200 characters or longer, an automatic junk heuristic gets turned on in python's SequenceMatcherの場合です。 このコードはあなたのために有効です:

from difflib import SequenceMatcher 

def partial_ratio(s1, s2): 
    """"Return the ratio of the most similar substring 
    as a number between 0 and 100.""" 

    if len(s1) <= len(s2): 
     shorter = s1 
     longer = s2 
    else: 
     shorter = s2 
     longer = s1 

    m = SequenceMatcher(None, shorter, longer, autojunk=False) 
    blocks = m.get_matching_blocks() 

    # each block represents a sequence of matching characters in a string 
    # of the form (idx_1, idx_2, len) 
    # the best partial match will block align with at least one of those blocks 
    # e.g. shorter = "abcd", longer = XXXbcdeEEE 
    # block = (1,3,3) 
    # best score === ratio("abcd", "Xbcd") 
    scores = [] 
    for (short_start, long_start, _) in blocks: 
     long_end = long_start + len(shorter) 
     long_substr = longer[long_start:long_end] 

     m2 = SequenceMatcher(None, shorter, long_substr, autojunk=False) 
     r = m2.ratio() 
     if r > .995: 
      return 100 
     else: 
      scores.append(r) 

    return max(scores) * 100.0