久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

python 正則表達式替換

瀏覽:115日期:2022-07-05 14:29:33

問題描述

最近遇到一個正則表達式替換的問題

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)

寫的不好,見笑了

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 吴江市| 安义县| 涪陵区| 银川市| 武城县| 东方市| 呼图壁县| 柯坪县| 丰原市| 广东省| 清流县| 辽阳县| 来凤县| 平安县| 绩溪县| 板桥市| 英吉沙县| 桓台县| 砀山县| 陕西省| 黎平县| 冕宁县| 浪卡子县| 阿尔山市| 虎林市| 克拉玛依市| 梓潼县| 孙吴县| 阳谷县| 皮山县| 共和县| 寿阳县| 丰县| 东辽县| 甘肃省| 嵊泗县| 开化县| 旺苍县| 朔州市| 中阳县| 高淳县|