2016-07-27 20 views
4

の一部を接触させて、非接触の検索私は答えに重複領域(*)と非重複領域を見つけるしたいと思います(+)および予測(o)。上述したように、私は、文字列</p> <pre><code>YHFLSPYVY # answer LSPYVYSPR # prediction +++******ooo YHFLSPYVS # answer VEYHFLSPY # prediction oo*******++ </code></pre> <p>のペアの2つの例を持っている二つの文字列

Pythonでどうすればいいですか?

私は例1のために得ることを望む答えがこの

import re 
# This is of example 1 
ans = "YHFLSPYVY" 
pred= "LSPYVYSPR" 
matches = re.finditer(r'(?=(%s))' % re.escape(pred), ans) 
print [m.start(1) for m in matches] 
#[] 

にこだわっている:

plus_len = 3 
star_len = 6 
ooo_len = 3 
+1

は、あなたが最初のオーバーラップをしたいですか?または最長重複? –

+0

* + oの文字列、またはplus_lenの値だけを指定しますか? –

+0

[longest common subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem)のように見えます –

答えて

3

それはdifflib.SequenceMatcher.find_longest_matchと簡単です:

from difflib import SequenceMatcher 

def f(answer, prediction): 
    sm = SequenceMatcher(a=answer, b=prediction) 
    match = sm.find_longest_match(0, len(answer), 0, len(prediction)) 
    star_len = match.size 
    return (len(answer) - star_len, star_len, len(prediction) - star_len) 

関数が戻ります3タプルの整数(plus_len, star_len, ooo_len)

f('YHFLSPYVY', 'LSPYVYSPR') -> (3, 6, 3) 
f('YHFLSPYVS', 'VEYHFLSPY') -> (2, 7, 2) 
+0

SOはスーパーインテリジェントな精神の軍隊のようなものです。 –

1

あなたはdifflib使用することができます。

import difflib 

ans = "YHFLSPYVY" 
pred = "LSPYVYSPR" 

def get_overlap(s1, s2): 
    s = difflib.SequenceMatcher(None, s1, s2) 
    pos_a, pos_b, size = s.find_longest_match(0, len(s1), 0, len(s2)) 
    return s1[pos_a:pos_a+size] 

overlap = get_overlap(ans, pred) 
plus = ans.replace(get_overlap(ans, pred), "") 
oo = pred.replace(get_overlap(ans, pred), "") 

print len(overlap) 
print len(plus) 
print len(oo) 
関連する問題

 関連する問題