python 正則表達式替換
問題描述
最近遇到一個正則表達式替換的問題
time數據里面的每條數據前面都有[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里面的數據數量是不一樣的
['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]=
補充:
錯誤的數據是在一起的,而且time里面的數據順序不相同,如下:
['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)
寫的不好,見笑了
相關文章:
1. javascript - jquery怎么給select option一個點擊時觸發的事件,如圖 如果選擇自定義觸發一個時間?2. java - android代碼重構:如何把app設置里的頭像UI做成通用的?3. 想找個php大神仿個網站。4. javascript - 怎樣限制同一個瀏覽器不能登錄兩個賬號5. java - 新手做一個安卓視頻播放器,想實現一個進度條,按鈕那種在視頻下方懸浮的功能,不知道思路!6. css3 - Typecho 后臺部分表單按鈕在 Chrome 下出現靈異動畫問題,求解決7. javascript - angular和jquery都用到了$符號,一起用會不會沖突?8. nginx配置server模塊的問題9. 如何將行內塊元素的內容垂直水平兩個方向居中?10. mysql優化 - 關于mysql分區
