python 正則表達(dá)式替換
問題描述
最近遇到一個(gè)正則表達(dá)式替換的問題
time數(shù)據(jù)里面的每條數(shù)據(jù)前面都有[0]= [1]= [2]= [3]=這個(gè)索引:
['time']={[0]={['status']=true,['ac']=1,['bg']=2},[1]={['status']=true,['ac']=1,['bg']=2},[2]={['status']=true,['ac']=1,['bg']=2},}
因?yàn)橐恍┰蚯懊娴乃饕龥]了,只能用正則來加上,問題是time里面的數(shù)據(jù)數(shù)量是不一樣的
['time']={{['status']=true,['ac']=1,['bg']=2},}['time']={{['status']=true,['ac']=1,['bg']=2},{['status']=true,['ac']=1,['bg']=2},}['time']={{['status']=true,['ac']=1,['bg']=2},{['status']=true,['ac']=1,['bg']=2},{['status']=true,['ac']=1,['bg']=2},}
有沒有方法自動在前面加順序的[0]= [1]= [2]= [3]=
補(bǔ)充:
錯(cuò)誤的數(shù)據(jù)是在一起的,而且time里面的數(shù)據(jù)順序不相同,如下:
['time1']={{['status']=true,['ac']=1,['bg']=2},},['time2']={{['status']=true,['ac']=1,['bg']=2},{['status']=true,['ac']=1,['bg']=2},},['time3']={{['status']=true,['ac']=1,['bg']=2},{['status']=true,['ac']=1,['bg']=2},{['status']=true,['ac']=1,['bg']=2},}
想改成:
['time1']={[0]={['status']=true,['ac']=1,['bg']=2},},['time2']={[0]={['status']=true,['ac']=1,['bg']=2},[1]={['status']=true,['ac']=1,['bg']=2},},['time3']={[0]={['status']=true,['ac']=1,['bg']=2},[1]={['status']=true,['ac']=1,['bg']=2},[2]={['status']=true,['ac']=1,['bg']=2},}
問題解答
回答1:>>> import re>>> s=’['time']={{['status']=true,['ac']=1,['bg']=2},{['status']=true,['ac']=1,['bg']=2},{['status']=true,['ac']=1,['bg']=2},}’>>> n=0>>> def repl(m): global n rslt=’[%d]=%s’%(n,m.group(0)) n+=1 return rslt>>> p=re.compile(r’{[^{}]+},’)>>> p.sub(repl,s)’['time']={[0]={['status']=true,['ac']=1,['bg']=2},[1]={['status']=true,['ac']=1,['bg']=2},[2]={['status']=true,['ac']=1,['bg']=2},}’回答2:
i = 0def func(x): global i s = ’[%d]=%s’ % (i,x) i += 1 return s import rea = ’['time']={{['status']=true,['ac']=1,['bg']=2},{['status']=true,['ac']=1,['bg']=2},}’print re.sub(’{['status'’,lambda m:func(m.group(0)),a)
寫的不好,見笑了
相關(guān)文章:
1. debian - docker依賴的aufs-tools源碼哪里可以找到啊?2. docker綁定了nginx端口 外部訪問不到3. node.js - nodejs debug問題4. docker 下面創(chuàng)建的IMAGE 他們的 ID 一樣?這個(gè)是怎么回事????5. docker網(wǎng)絡(luò)端口映射,沒有方便點(diǎn)的操作方法么?6. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?7. docker - 如何修改運(yùn)行中容器的配置8. docker-compose中volumes的問題9. golang - 用IDE看docker源碼時(shí)的小問題10. docker-machine添加一個(gè)已有的docker主機(jī)問題
