在Python中编辑JavaScript文件时出现问题

问题描述

我正在用Python编辑javascript文件,我已经做了很多工作,但是我处于关键时刻,你能帮忙吗?

我要编辑的部分:

                    "589": {
                        p: "no-repeat",c: 97,q: "100% 100%",bS: 420,cP: "garson",r: "none",d: 138,cQ: 1,gg: "0",cR: 1,aP: "pointer",h: "553",i: "garson2",bF: "578",aI: 35,j: "absolute",x: "visible",aA: {
                            a: [{
                                d: 1.1,p: 1,g: 1,f: 1
                            },{
                                p: 4,h: "474"
                            },h: "476"
                            }]
                        },k: "div",aJ: 35,dB: "img",z: 23,Q: 16,aK: 35,R: "rgba(0,0.411)",S: 5,a: 140,aL: 35,T: 4,b: 2
                    }

javascript文件中还有更多类似的块。 i: "garson2"这个词也不是固定的,但是我可以得到这个值。使用术语i: "garson2",我想在该术语所在的块中使r: "none"成为变量r: "inline"。我该怎么做?注意:r: "none"i: "garson2"间的术语也是可变的。

解决方法

您可以为此使用肯定的前瞻性断言,并使用re.sub()进行替换。

r: "none"(?=[^{}]+i: "garson2")

Demo

示例

import re
text="""
"589": {
                        p: "no-repeat",c: 97,q: "100% 100%",bS: 420,cP: "garson",r: "none",d: 138,cQ: 1,gg: "0",cR: 1,aP: "pointer",h: "553",i: "garson2",bF: "578",aI: 35,j: "absolute",x: "visible",aA: {
                            a: [{
                                d: 1.1,p: 1,g: 1,f: 1
                            },{
                                p: 4,h: "474"
                            },h: "476"
                            }]
                        },k: "div",aJ: 35,dB: "img",z: 23,Q: 16,aK: 35,R: "rgba(0,0.411)",S: 5,a: 140,aL: 35,T: 4,b: 2
                    }
"""

print(re.sub(r'r: "none"(?=[^{}]+i: "garson2")','r: "inline"',text))

输出

"589": {
                        p: "no-repeat",r: "inline",b: 2
                    }
,
  var t: CATransform3D = CATransform3DIdentity
                    t = CATransform3DRotate(t,270 * CGFloat.pi / 180,1) // rotate by z axis
                    t = CATransform3DRotate(t,-50 * CGFloat.pi / 180,1,0) // rotate by y axis
                    t.m34 = 1.0 / -500
                    logLabel.transform3D = t // implement sequence of rotations to label
                    contentView.addSubview(logLabel)

我尝试过,就像您在代码中所说的那样。但是我有一个错误。抱歉,我没有提前编写此部分,我想我已经延长了解决方案所需的时间,而不了解它。

我得到的错误是:

    r = re.compile(r'r: "none"(?=[^{}]+i: "garson2")')
    with open('static/js/cafeproje_hype_generated_script.js') as f:
        contents = f.read()

    contents = r.sub(r'r: "none"(?=[^{}]+i: "garson2")',contents)

    with open('static/js/cafeproje_hype_generated_script.js','w') as f:
        f.write(contents)

    return print ("Garson Ekleme İşlemi Tamam\n\nEklenen Garson İsmi:\t{}\nEklenen Garson Sırası:\t{}".format(garson_isim,garson_sira))