将字符串插入javascript文件的特定部分

时间:2017-11-18 00:34:38

标签: regex string python-2.7

我需要通过插入一个带有python的字符串来更改javascript文件的一个特定部分。以下是javascript文件的一小部分示例。

//----------------------------------------Peter Lighting Priorities-----------------------------------------------------
/*

// Lighting low prios for everything else//
peter_RenderBoy_lighting_lowPrios = {
    "fromProductionGroups" : ["peter_RenderBoy_lighting"],
    "matchFilters" : [
        {"user": "", "name": ""}     

    ],
    "toProductionGroup" : "",
    "priority" : 3

};

moveAndPrioritise(peter_RenderBoy_lighting_lowPrios);

// lighting normal and Approved LFL shots (emailed at 8pm) //
peter_RenderBoy_lighting_normalPrios = {
    "fromProductionGroups" : ["peter_RenderBoy_lighting"],
    "matchFilters" : [
        {"user": "", "name": ""}     

    ],
    "toProductionGroup" : "",
    "priority" : 2

};

moveAndPrioritise(peter_RenderBoy_lighting_normalPrios);

以下是javascript的相同示例,其中以粗体显示字符串“ INSERT_STRING_HERE ”,需要插入:

//----------------------------------------Peter Lighting Priorities-----------------------------------------------------
/*

// Lighting low prios for everything else//
peter_RenderBoy_lighting_lowPrios = {
    "fromProductionGroups" : ["peter_RenderBoy_lighting"],
    "matchFilters" : [
        {"user": "", "name": ""}     

    ],
    "toProductionGroup" : "",
    "priority" : 3

};

moveAndPrioritise(peter_RenderBoy_lighting_lowPrios);

// lighting normal and Approved LFL shots (emailed at 8pm) //
peter_RenderBoy_lighting_normalPrios = {
    "fromProductionGroups" : ["peter_RenderBoy_lighting"],
    "matchFilters" : [
        {"user": "", "name": "***INSERT_STRING_HERE***"}     

    ],
    "toProductionGroup" : "",
    "priority" : 2

};

moveAndPrioritise(peter_RenderBoy_lighting_normalPrios);

这是我到目前为止的尝试,这只是表明我已经导入了正则表达式,但是由于放弃了我的努力,并且我试图循环遍历javascript文件,但不知道如何继续实现我需要的是什么:

import re
javascript_file = open('/depts/wranglers/frankie/farmtools/priorities/autoHook.js')
for line in javascript_file:
    if '// lighting normal and Approved LFL shots (emailed at 8pm) //' in line:

1 个答案:

答案 0 :(得分:1)

当您看到该注释行时,请设置变量。然后,当您看到包含要替换的模式的行时,请检查变量是否已设置,然后进行替换。

with open('/depts/wranglers/frankie/farmtools/priorities/autoHook.js') as javascript_file, \
     open('/depts/wranglers/frankie/farmtools/priorities/autoHook.new.js') as new_file
    section_found = False
    for line in javascript_file:
        if '// lighting normal and Approved LFL shots (emailed at 8pm) //' in line:
            section_found = True
        elif '{"user": "", "name": ""}' and section_found:
            line = line.replace('"name": ""', '"name": "INSERT_STRING_HERE"')
            section_found = False
        new_file.write(line + "\n")