首頁  >  問答  >  主體

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},}
淡淡烟草味淡淡烟草味2711 天前529

全部回覆(2)我來回復

  • 黄舟

    黄舟2017-05-18 11:00:52

    雷雷

    回覆
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-18 11:00:52

    i = 0
    def func(x):
        global i
        s = '[%d]=%s' % (i,x)
        i += 1
        return s 
    import re
    a = '["time"]={{["status"]=true,["ac"]=1,["bg"]=2},{["status"]=true,["ac"]=1,["bg"]=2},}'
    print re.sub('\{\["status"',lambda m:func(m.group(0)),a)

    寫的不好,見笑了

    回覆
    0
  • 取消回覆