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

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

python 正則表達式替換

瀏覽:120日期: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 編程
相關文章:
主站蜘蛛池模板: 北流市| 莆田市| 乌拉特中旗| 桐柏县| 洪江市| 始兴县| 孟津县| 凌海市| 屏南县| 赤峰市| 阜新| 安新县| 绥中县| 台东县| 德江县| 新安县| 庐江县| 廉江市| 灵武市| 民县| 沅陵县| 甘德县| 舒兰市| 绍兴县| 广丰县| 六枝特区| 文安县| 天津市| 青冈县| 涟水县| 交城县| 南皮县| 山丹县| 大荔县| 隆子县| 招远市| 伊宁市| 丹江口市| 肇州县| 姚安县| 庆安县|