使用:
from Bio import pairwise2
from itertools import groupby
def maxConnectedSubstrings(strA, strB):
alignment = pairwise2.align.globalxx(strA, strB)[0]
grouped = groupby(zip(alignment.seqA, alignment.seqB), key=lambda p: p[0] == p[1])
return [''.join(ca for ca,cb in g) for k,g in grouped if k]
print( maxConnectedSubstrings('abcdefgh', 'abudesh') )
解释
首先,我们需要对序列进行对齐。执行alignment = pairwise2.align.globalxx(strA, strB)[0]
的结果如下:
alignment.seqA = 'abcdefgh'
alignment.seqB = 'abude-sh'
对齐算法找到了在序列中添加'-'
以对齐它们的最佳方法。
然后,我们在zip(alignment.seqA, alignment.seqB)
上使用groupby
。 zip(...)
是一系列成对出现的元素(来自seqA的字符,来自seqB的字符)。 我们使用lambda p: p[0] == p[1]
作为键来将这些成对出现的元素进行分组,结果如下:
grouped = groupby(zip(alignment.seqA, alignment.seqB), key=lambda p: p[0] == p[1])
grouped = [
(True, [('a', 'a'),
('b', 'b')]),
(False, [('c', 'u')]),
(True, [('d', 'd'),
('e', 'e')]),
(False, [('f', '-'),
('g', 's')]),
(True, [('h', 'h')])
]
最后,我们丢弃False组,并连接每个True组中的字母。
print( pairwise2.align.globalxx('abcdefgh', 'abudesh') )
会输出[Alignment(seqA='abc-defg-h', seqB='ab-ude--sh', score=5.0, start=0, end=10), Alignment(seqA='abcdefg-h', seqB='abude--sh', score=5.0, start=0, end=9), Alignment(seqA='abc-defgh', seqB='ab-ude-sh', score=5.0, start=0, end=9), Alignment(seqA='abcdefgh', seqB='abude-sh', score=5.0, start=0, end=8), Alignment(seqA='abc-defgh', seqB='ab-udes-h', score=5.0, start=0, end=9), Alignment(seqA='abcdefgh', seqB='abudes-h', score=5.0, start=0, end=8)]
。 - Stef