识别2个字符串之间的短匹配序列

时间:2014-05-08 17:00:03

标签: python python-2.7 string-matching

我有以下代码:

for k, (j,k) in enumerate (zip(line1_u,line2_u_rev_comp)):
    if j==k:
        Match1+=1 
    if j== 'N' or k == 'N':
        Unknown1+=1
    if j != k:
        Different1+=1

这需要2行(line1_u和line2_u_rev_comp)并逐个字符地比较它们以确定它们是否匹配,具有将其置于未知类别中的N或不同的N.我想要的是,以及计算每一个是确定连续10个字符或更多匹配。怎么可以这样做?非常感谢代码的解释。

2 个答案:

答案 0 :(得分:0)

看一下python中的difflib模块:https://docs.python.org/2/library/difflib.html。使用find_longest_match查找最长的公共子序列。

答案 1 :(得分:0)

您应该查看itertools.groupby

from collections import defaultdict
from itertools import groupby

def class_chars(chrs):
    if 'N' in chrs:
        return 'unknown'
    elif chrs[0] == chrs[1]:
        return 'match'
    else:
        return 'not_match'

s1 = 'aaaaaaaaaaN123bbbbbbbbbbQccc'
s2 = 'aaaaaaaaaaN456bbbbbbbbbbPccc'
n = 0
consec_matches = []
chars = defaultdict(int)

for k, group in groupby(zip(s1, s2), class_chars):
    elems = len(list(group))
    chars[k] += elems
    if k == 'match':
        consec_matches.append((n, n+elems-1))
    n += elems

print chars
print consec_matches
print [x for x in consec_matches if x[1]-x[0] >= 9]

输出:

defaultdict(<type 'int'>, {'not_match': 4, 'unknown': 1, 'match': 23})
[(0, 9), (14, 23), (25, 27)]
[(0, 9), (14, 23)]