Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python查找字符串中重叠序列的数量?_Python - Fatal编程技术网

如何使用Python查找字符串中重叠序列的数量?

如何使用Python查找字符串中重叠序列的数量?,python,Python,我有一个很长的序列,我想知道一些子序列在这个序列中出现的频率 我知道,但它只计算非重叠序列 是否存在同样计算重叠序列的类似功能?这将有助于您: 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

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

我知道,但它只计算非重叠序列

是否存在同样计算重叠序列的类似功能?

这将有助于您:

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))
请看这里:


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

一种简单易懂的方法是:

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可以处理布尔型整数的事实。

作为编写自己的搜索函数的替代方法,您可以使用
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

我今天了解到,您可以使用运行索引获取下一个出现的子字符串:

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

您可能想查看@moose您知道子序列之前的发生次数吗?将循环的行替换为。。。new_st=st[i:];如果new_st.startswith(pinder):匹配.append(i)no,我猜,因为我已经被用来检查从i开始的字符串st.find(pinder,i,i+len(pinder))的特定块,所以创建子字符串和赋值将只是一个开销。我将投票支持这个。比我自己的好多了。一个简单的len(匹配项)将给出结果。一行代码:return len(re.finditer(r'(?=(%s))'%re.escape(needle),haystack))。。。极好:)@DhruvPathak
TypeError:callable iterator类型的对象没有len()
With
Lsub=len(sub)
如果字符串[i:i+Lsub]==sub:
和长度为298的字符串,它运行时间为1.17秒,而代码运行时间为4秒(10000次迭代)-此外,sum()速度慢,sum()函数运行时间为sum()我的第一个版本使用了Lsub,但我牺牲了速度来与这个新版本进行比较,因为OP从未声明他有性能要求。我从来没有分析过sum,所以我不能保证它的速度很慢(我看不出原因),但如果是这样,itertools.reduce+operator.add就可以了。我从成员gnibbler那里学到sum()的速度很慢:()(查看评论)。正如您将在这些评论中看到的,正是这个原因解释了sum()和reduce()的缓慢性,这是我的第一个假设。但是itertools.reduce()与reduce()不同:它没有二次性能,因为它不会每次都创建一个新列表。itertools模块中的所有功能都在幕后使用生成器。。。问题在于Python 2.7.1文档中的itertools模块中没有reduce(),Python 3.2文档中也没有reduce()。在Python3.2中,reduce()仅出现在functools()模块中,它似乎与Python2.x中之前的函数相同,即
例如,reduce(lambda x,y:x+y,[1,2,3,4,5])计算(((1+2)+3)+4)+5)。
在Python2.x中,functools.reduce():这是与reduce()相同的函数。在这个模块中,可以使用它来编写与Python3更加兼容的代码。