python 正則表達(dá)式替換
問(wèn)題描述
最近遇到一個(gè)正則表達(dá)式替換的問(wèn)題
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)橐恍┰蚯懊娴乃饕龥](méi)了,只能用正則來(lái)加上,問(wè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},}
有沒(méi)有方法自動(dòng)在前面加順序的[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},}
問(wèn)題解答
回答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)
寫的不好,見(jiàn)笑了
相關(guān)文章:
1. javascript - sublime快鍵鍵問(wèn)題2. javascript - immutable配合react提升性能?3. css - 寫頁(yè)面遇到個(gè)布局問(wèn)題,求大佬們幫解答,在線等,急!~4. javascript - nodejs關(guān)于進(jìn)程間發(fā)送句柄的一點(diǎn)疑問(wèn)5. Apache 已經(jīng)把網(wǎng)站根目錄的改為allow from all了,但是服務(wù)器還是不能訪問(wèn)?6. 實(shí)現(xiàn)bing搜索工具urlAPI提交7. 配置Apache時(shí),添加對(duì)PHP的支持時(shí)語(yǔ)法錯(cuò)誤8. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽(tīng)數(shù)據(jù)變化9. javascript - 移動(dòng)端上不能實(shí)現(xiàn)拖拽布局嗎?10. phpstudy8.1支持win11系統(tǒng)嗎?

網(wǎng)公網(wǎng)安備