2016-07-27 161 views
3

我有一些字符串,其中每個字符串都是一個或多個字符串的副本。例如:如何將字符串拆分爲重複的子字符串

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

我想這樣的字符串分割成一個列表,以便每個元素只是有重複的部分。例如:

splitstring(L) ---> ["hello", "hello", "hello"] 
splitstring(M) ---> ["good"] 
splitstring(N) ---> ["where", "where"] 
splitstring(O) ---> ["ant", "ant"] 

由於字符串每個字符長度大約爲1000個字符,所以如果這個字符相當快,那也是很好的。

請注意,在我的情況下,重複都從字符串的開始處開始,並且它們之間沒有間隔,所以它比在字符串中查找最大重複的一般問題要簡單得多。

如何做到這一點?

+0

看看這個[問題](http://stackoverflow.com/questions/11090289/find-longest-repetitive-sequence-i n-a-string)我認爲你正在尋找類似的東西?此外,這種方法給出的複雜度是O(n),所以它應該是非常快的按照您的要求。 –

+0

@MridulKashyap我的問題非常簡單,因爲我的重複從字符串的開頭開始,並且在它們之間沒有任何間隔。 – eleanora

回答

4

使用正則表達式來查找重複的話,那麼只需要創建一個適當長度的列表:

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

好主意,我也想過做這樣的事情。 – alex

0

該方法我會用:

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) 

給出與相應的可變以下輸出:

hello 
good 
where 
1

嘗試此。它不是縮減列表,而是專注於找到最短的模式,然後通過重複該模式適當的次數創建一個新列表。

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'] 
+0

我不知道這三件事中的任何一件,謝謝先生。我會測試這個並編輯 – BusyAnt

0

假設重複單詞的長度大於1長這會工作:

a = "hellohellohello" 

def splitstring(string): 
    for number in range(1, len(string)): 
     if string[:number] == string[number:number+number]: 
      return string[:number] 
    #in case there is no repetition 
    return string 

splitstring(a) 
+2

它在「aabaab」上失敗。 – cogitovita

0
#_*_ coding:utf-8 _*_ 
import re 
''' 
refer to the code of Gábor Erds below 
''' 

N = "wherewhere" 
cnt = 0 
result = '' 
countN = 0 
showresult = [] 

for i in range(1,len(N)+1): 
    if cnt <= len(re.findall(N[0:i],N)): 
     cnt = len(re.findall(N[0:i],N)) 
     result = re.findall(N[0:i],N)[0] 
     countN = len(N)/len(result) 
for i in range(0,countN): 
    showresult.append(result) 
print showresult 
+0

請爲您的代碼與[GáborErdős的帖子](http://stackoverflow.com/a/38608219/5488275)不同之處添加說明。 –