如何将字符串拆分为重复的子字符串

2024-09-23 14:29:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有字符串,每个字符串都是某个字符串的一个或多个副本。例如:

L = "hellohellohello"
M = "good"
N = "wherewhere"
O = "antant"

我想把这样的字符串拆分成一个列表,这样每个元素只包含重复的部分。例如:

^{pr2}$

由于每个字符串大约有1000个字符长,所以如果速度也相当快的话,那就太好了。在

注意,在我的例子中,重复都是从字符串的开头开始的,它们之间没有间隔,所以这比在字符串中寻找最大重复次数的一般问题简单得多。在

怎么能做到这一点?在


Tags: 字符串元素列表间隔副本次数速度例子
3条回答

使用regex查找重复单词,然后简单地创建一个适当长度的列表:

def splitstring(string):
    match= re.match(r'(.*?)(?:\1)*$', string)
    word= match.group(1)
    return [word] * (len(string)//len(word))

我将采用的方法是:

import re

L = "hellohellohello"
N = "good"
N = "wherewhere"

cnt = 0
result = ''
for i in range(1,len(L)+1):
    if cnt <= len(re.findall(L[0:i],L)):
        cnt = len(re.findall(L[0:i],L))
        result = re.findall(L[0:i],L)[0]

print(result)

使用相应的变量给出以下输出:

^{pr2}$

试试这个。它不是剪切列表,而是集中精力寻找最短的模式,然后通过重复这个模式适当的次数来创建一个新的列表。在

def splitstring(s):
    # searching the number of characters to split on
    proposed_pattern = s[0]
    for i, c in enumerate(s[1:], 1):
        if proposed_pattern == s[i:(i+len(proposed_pattern))]:
            # found it
            break
        else:
            proposed_pattern += c
    else:
        print 'found no pattern'
        exit(1)
    # generating the list
    n = len(proposed_pattern)
    return [proposed_pattern]*(len(s)//n)


if __name__ == '__main__':
    L = 'hellohellohellohello'
    print splitstring(L)  # prints ['hello', 'hello', 'hello', 'hello']

相关问题 更多 >