<p>这里有一个丑陋的解决方案:</p>
<pre><code>def parse(s,L=None):
do_return=L is None
if(not s):
return
if(do_return):
L=[]
substr=s[0]
for i in range(1,len(s)-1):
if s[:i] in s[i:]:
substr=s[:i]
else:
L.append(substr)
parse(s.replace(substr,''),L=L)
break
else:
L.append(s)
if(do_return):
LL=[(ss,s.count(ss)) for ss in L] #Count the number of times each substring appears
LLL=[]
#Now some of our (unmatched) substrings will be adjacent to each other.
#We should merge all adjacent unmatched strings together.
while LL:
LLL.append(LL.pop(0))
while LLL[-1][1] == 1 and LL: #check if next is unmatched
if(LL[0][1]==1): #unmatched, merge and remove
LLL[-1]=(LLL[-1][0]+LL[0][0],1)
LL.pop(0)
else: #matched, keep on going.
break
d={}
for k,v in LLL:
d[k]=v
return d
S='eg,abcgdfabc'
print parse(S) #{ 'e':1, 'g':2, ',':1, 'abc': 2, 'df', 1}
</code></pre>
<p>当然,这并不像您所期望的那样工作,因为g匹配两次(因为它是贪婪的)。。。在</p>
<p>如果您总是想以3人一组的方式进行迭代,这会变得更简单(更漂亮):</p>
^{pr2}$