如何在Python中找到String中重叠序列的数量?

时间:2011-07-27 12:07:04

标签: python

我有一个很长的序列,我想知道一些子序列在这个序列中出现的频率。

我知道string.count(s, sub),但它只计算非重叠序列。

是否存在也计算重叠序列的类似函数?

4 个答案:

答案 0 :(得分:10)

作为编写自己的搜索功能的替代方法,您可以使用re模块:

In [22]: import re

In [23]: haystack = 'abababa baba alibababa'

In [24]: needle = 'baba'

In [25]: matches = re.finditer(r'(?=(%s))' % re.escape(needle), haystack)

In [26]: print [m.start(1) for m in matches]
[1, 3, 8, 16, 18]

以上打印出所有(可能重叠)匹配的起始位置。

如果您需要的只是计数,以下应该可以解决问题:

In [27]: len(re.findall(r'(?=(%s))' % re.escape(needle), haystack))
Out[27]: 5

答案 1 :(得分:6)

一个简单易懂的方法是:

def count(sub, string):
    count = 0
    for i in xrange(len(string)):
        if string[i:].startswith(sub):
            count += 1
    return count

count('baba', 'abababa baba alibababa')
#output: 5

如果你喜欢简短的片段,你可以使它不那么可读但更聪明:

def count(subs, s):
    return sum((s[i:].startswith(subs) for i in xrange(len(s))))

这使用了Python可以像处理整数一样处理布尔值的事实。

答案 2 :(得分:1)

这可以帮到你:

matches =[]
st = 'abababa baba alibababa'
needle = 'baba'
for i in xrange(len(st)-len(needle)+1): 
   i = st.find(needle,i,i+len(needle))
   if(i >= 0):
     matches.append(st.find(needle,i,i+len(needle)))
print(str(matches))

在此处查看:http://codepad.org/pmkKXmWB

没有针对长字符串进行基准测试,看看它是否足够有效供您使用。

答案 3 :(得分:0)

我今天了解到你可以使用一个运行索引来获取下一个子字符串:

string = 'bobobobobobobob' # long string or variable here
count = 0
start = 0
while True:
    index = string.find('bob', start)
    if index >= 0:
        count += 1
        start += 1
    else:
        break
print(count)

返回7