2017-11-18 96 views
0

我需要通過插入一個字符串,用python來更改JavaScript文件的一個特定部分。這是一個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: 
+0

Python腳本應該如何知道應該在哪一行插入字符串? – Barmar

回答

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") 
相關問題