Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.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_String_Search_Substring - Fatal编程技术网

Python 查找子字符串在字符串中连续出现的最多次数

Python 查找子字符串在字符串中连续出现的最多次数,python,string,search,substring,Python,String,Search,Substring,我有一个很长的字符串,我不仅要找出这些字符的子字符串是否存在于较大的字符串中,而且还要找出连续实例的最长运行时间 例如。。。在下面的代码片段中,我发现我可以使用“count”来查看子字符串b在a中出现了多少次。结果是5。然而,我试图确定的是最长的连续运行,即3(其中“abc”出现在中间背靠背)。我很难理解这个逻辑。如有任何建议,将不胜感激 a = "abcxyzabcabcabcxyzabcxyz" b = "abc" total = a.count(b) print(total) 一种

我有一个很长的字符串,我不仅要找出这些字符的子字符串是否存在于较大的字符串中,而且还要找出连续实例的最长运行时间

例如。。。在下面的代码片段中,我发现我可以使用“count”来查看子字符串b在a中出现了多少次。结果是5。然而,我试图确定的是最长的连续运行,即3(其中“abc”出现在中间背靠背)。我很难理解这个逻辑。如有任何建议,将不胜感激

a = "abcxyzabcabcabcxyzabcxyz"

b = "abc"

total = a.count(b)

print(total)

一种可能且简单的解决方案是使用python
index
函数来标识子字符串的最近索引。从那里,您可以继续向前搜索子字符串,直到找到不再显示的点,然后再次调用
index
以向前跳过

例如:

a = "abcxyzabcabcabcxyzabcxyz"
b = "abc"

curr_index = a.index(b)
longest_count = 0
current_count = 0

while curr_index < len(a):
    if a[curr_index : curr_index + len(b)] == b:
        curr_index += len(b)
        current_count += 1
    else:
        if longest_count < current_count:
            longest_count = current_count
        try:
            curr_index = a.index(b, curr_index)
        except ValueError:
            # Substring no longer found in string slice
            break
        current_count = 0

if longest_count < current_count:
    longest_count = current_count

print(longest_count)
a=“abcxyzabcabcxyzabcxyz”
b=“abc”
当前索引=a.索引(b)
最长计数=0
当前计数=0
而当前指数

这只返回最长的重复计数,但不返回开始位置。但是,添加该功能并不重要。

使用while循环应该相当简单:

def func(a, b): 
    n = 1 
    while b*n in a: 
        n += 1 
    return n - 1 

继续呼叫
a.index
on
b
,使用适当的索引。如果索引是子集的开始,则处于相同的运行中。否则,开始新的运行:

def longest_run(string, pattern):
    longest = 0
    current = 0
    start = 0
    while True:
        try:
            ind = string.index(pattern, start)
            if ind == start:
                current += 1
            else:
                if current > longest:
                    longest = current
                current = 1
            start += len(pattern)
        except ValueError:
            return longest

您可以将
re.findall
与匹配
b
一次或多次的模式一起使用(使用
re.escape
防止
b
被解释为正则表达式),然后将返回字符串映射到
len
并将其传递到
max
以获得最长匹配的长度,然后将该长度除以
b
的长度,得到重复
b
的次数:

import re
max(map(len, re.findall('(?:%s)+' % re.escape(b), a))) // len(b)

您可以继续使用索引进行搜索,对于任何合理的字符串,可能都会非常快,但在算法上效率很低+1如果字符串很长,则此解决方案可能会因执行的重复搜索次数而内存不足或运行速度非常慢,但如果内存不足,则字符串
a
已经占用了一半的内存。Downvoter:在Python中,子字符串检查是高度优化的,因此在实践中,我会惊讶地看到一个比这个更快的版本,尽管算法效率低下(但很高兴被证明是错误的)。