最频繁的带有公差的子串

时间:2013-11-15 02:01:10

标签: python string substring match frequency

我试图在字符串上找到最频繁的子字符串(某个长度为L),但是允许某个阈值或错误T(在子字符串的amy位置),显然不会长于L本身。但是,到目前为止我还没有取得任何成功。我怎么能完成代码?

stn='KLHLHLHKPLHLHLPHHKLH'
L = 4 #(lenght of the pattern)
T = 1 #(maximum tolerance or permitted error in any position of the query pattern) 

pattcount = {}
for n in range(len(stn)- L+1):
patt = stn[n:n+L]
s_ = stn[i:i+len(patt)]
if LevenshteinDistance(s_, patt) == T:
pattcount[patt] = pattcount[patt] + 1 if pattcount.has_key(patt) else 1

max = 0
max_patt = []
for p,v in pattcount.iteritems():
if v > max:
max_patt = [p]
max = v
elif v == max:
max_patt += [p]
print (" ".join(max_patt))

因此,例如,如果最常见的是KLH,那么HLH,PLH,KLP,KPH的频率如何膨胀KLH的频率(为了报告)?

1 个答案:

答案 0 :(得分:0)

>>> from Levenshtein import distance
>>> from collections import defaultdict
>>> tups = [stn[i:i+L] for i in range(0, len(stn) - (L - 1))]
>>> print tups
['KLHL', 'LHLH', 'HLHL', 'LHLH', 'HLHK', 'LHKP', 'HKPL', 'KPLH', 'PLHL', 'LHLH',
 'HLHL', 'LHLP', 'HLPH', 'LPHH', 'PHHK', 'HHKL', 'HKLH']
>>> d = defaultdict(list)
>>> [d[x].append(y) for x in tups for y in tups 
                                  if x is not y and distance(x, y) <= T]
>>> print d
defaultdict(<type 'list'>, {
               'KLHL': ['HLHL', 'PLHL', 'HLHL'], 
               'LHLP': ['LHLH', 'LHLH', 'LHKP', 'LHLH'], 
               'HLHK': ['HLHL', 'HLHL'], 
               'HLHL': ['KLHL', 'HLHK', 'PLHL', 'KLHL', 'HLHK', 'PLHL'], 
               'LHKP': ['LHLP'], 
               'LHLH': ['LHLP', 'LHLP', 'LHLP'], 
               'PLHL': ['KLHL', 'HLHL', 'HLHL']})
>>> s = sorted(d.iterkeys(), key=lambda k: len(d[k]), reverse=True)
>>> print s
['HLHL', 'LHLP', 'KLHL', 'LHLH', 'PLHL', 'HLHK', 'LHKP']