[英]How to find the largest number of times a word is repeated consecutively in a given string?
[英]Find which term is repeated in a string, when given a known number of N occurrences in the string
有什么方法可以执行以下操作,而无需使用蛮力之类的工具?
str = "abbcccddddefefef"
N = 3
repeated_term = func(str,N)
print(repeated_term )
> ['c','ef']
N = 2
term = func(str,N)
print(term)
> ['b', 'dd', 'fe'] # Thanks to @blhsing for the correction!
等等...
您可以安装PyPi正则表达式模块 (该模块支持可变宽度后向模式),以使用正则表达式查找精确重复N-1次的序列:
import regex
def func(s, N):
return regex.findall(r'(?=(.+?)(?:\1){%d}(?!\1))(?<!\1)' % (N - 1), s)
以便:
func("abbcccddddefefef", 3)
返回:
['c', 'ef']
然后:
func("abbcccddddefefef", 2)
返回:
['b', 'dd', 'fe']
请注意,您对N = 2的预期输出是不正确的,因为'dd'
和'fe'
都恰好出现了2次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.