2017-10-04 24 views
0

我想要一個代碼返回兩個字符串中所有相似序列的和。我寫了下面的代碼,但它只返回其中的一個Python在字符串中找到類似的序列

from difflib import SequenceMatcher 
a='Apple Banana' 
b='Banana Apple' 
def similar(a,b): 
    c = SequenceMatcher(None,a.lower(),b.lower()).get_matching_blocks() 
    return sum([c[i].size if c[i].size>1 else 0 for i in range(0,len(c)) ]) 
print similar(a,b) 

和輸出將是

6 

我希望它是:11

回答

0

get_matching_blocks()返回最長連續匹配子序列。這裏最長的匹配子序列是「香蕉」在兩個字符串,長度爲6,因此它返回6.

嘗試此代替:

def similar(a,b): 
    c = 'something' # Initialize this to anything to make the while loop condition pass for the first time 
    sum = 0 

    while(len(c) != 1): 
     c = SequenceMatcher(lambda x: x == ' ',a.lower(),b.lower()).get_matching_blocks() 

     sizes = [i.size for i in c] 
     i = sizes.index(max(sizes)) 
     sum += max(sizes) 

     a = a[0:c[i].a] + a[c[i].a + c[i].size:] 
     b = b[0:c[i].b] + b[c[i].b + c[i].size:] 

    return sum 

這種「減去」的串的匹配部分,並再次匹配它們,直到len(c)爲1,這將在沒有更多匹配時發生。

但是,此腳本不會忽略空格。爲了做到這一點,我使用的建議從this other SO answer:剛纔你預處理前的字符串它們傳遞給函數,像這樣:

a = 'Apple Banana'.replace(' ', '') 
b = 'Banana Apple'.replace(' ', '') 

可以包括在函數內部這部分了。

+0

試圖設置一個'=「蘋果香蕉Orange''&'B =」橙色香蕉蘋果',那麼結果'13'? – thewaywewere

+0

我已經更新了我的答案以處理更一般的情況,包括您提到的情況。感謝您指出! – Antimony

+0

如果你移動 sizes = [i.size for i in c] i = sizes.index(max(sizes)) inside while while循環效果更好 –

0

當我們編輯你的代碼這一點,會告訴我們6是來自:

from difflib import SequenceMatcher 
a='Apple Banana' 
b='Banana Apple' 
def similar(a,b): 
    c = SequenceMatcher(None,a.lower(),b.lower()).get_matching_blocks() 
    for block in c: 
     print "a[%d] and b[%d] match for %d elements" % block 
print similar(a,b) 

一[6]和b [0]爲匹配6個元素

一個[12]和B [12]爲匹配0個元素

0

我做了小改動,將代碼和它的工作就像一個魅力,謝謝@Antimony

def similar(a,b): 
    a=a.replace(' ', '') 
    b=b.replace(' ', '') 

    c = 'something' # Initialize this to anything to make the while loop condition pass for the first time 
    sum = 0 
    i = 2 
    while(len(c) != 1): 
     c = SequenceMatcher(lambda x: x == ' ',a.lower(),b.lower()).get_matching_blocks() 
     sizes = [i.size for i in c] 
     i = sizes.index(max(sizes)) 
     sum += max(sizes) 
     a = a[0:c[i].a] + a[c[i].a + c[i].size:] 
     b = b[0:c[i].b] + b[c[i].b + c[i].size:] 
    return sum 
相關問題