python 正則表達式替換
問題描述
最近遇到一個正則表達式替換的問題
time數(shù)據(jù)里面的每條數(shù)據(jù)前面都有[0]= [1]= [2]= [3]=這個索引:
['time']={[0]={['status']=true,['ac']=1,['bg']=2},[1]={['status']=true,['ac']=1,['bg']=2},[2]={['status']=true,['ac']=1,['bg']=2},}
因為一些原因前面的索引沒了,只能用正則來加上,問題是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]=
補充:
錯誤的數(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. PHP類中的$this2. python - Django Admin創(chuàng)建不關(guān)聯(lián)任何model的自定義頁面3. javascript - h5分享鏈接到qq或者微信時有一個縮略圖還有一些說明文字,這個要怎么去修改里面的圖片和內(nèi)容?4. javascript 如何下載一個excel文件 ?5. 誰有mysql5.7安裝的詳細教程6. mysql - 看這條sql有可能被注入嗎7. python - Django操作數(shù)據(jù)庫遇到問題,無法查詢更新后的數(shù)據(jù)8. 請問是對象還是數(shù)組9. android - 第三方App調(diào)用高德地圖,總是直接進入到導(dǎo)航頁面,有沒有辦法進入首頁?10. python2.7 - Python安裝模組不成功
