国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

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

python 正則表達式替換

瀏覽:99日期: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 編程
相關文章:
主站蜘蛛池模板: 化隆| 太原市| 崇礼县| 磐安县| 历史| 文登市| 阿克陶县| 邵东县| 新巴尔虎右旗| 巴中市| 凤冈县| 临沂市| 达拉特旗| 宁夏| 涟水县| 兰溪市| 托克托县| 嘉黎县| 巴彦淖尔市| 城固县| 峨山| 钟山县| 佛坪县| 钟山县| 西乡县| 沙田区| 阳原县| 额济纳旗| 吴忠市| 榆社县| 合水县| 永胜县| 桂林市| 公主岭市| 栖霞市| 兴义市| 和龙市| 威信县| 平潭县| 周口市| 同德县|