1

我正在尝试在由起始键指定的特定行上应用特定的正则表达式:现在我的文件内容在 python 变量 my_config 中


file content
---------------------------------------------
[paths]
path_jamjs: C:/Users/[changeUsername]/AppData/Roaming/npm/node_modules/jamjs/bin/jam.js
path_php: C:/[changeUsername]/php/php.exe

values to replace
---------------------------------------------
"path_jamjs": { "changeUsername": "Te" },
"path_php": { "changeUsername": "TeS" },

with open ("my.ini", "r") as myfile:
  my_config = myfile.read()

如何对 my_config 中的整个文件内容应用正则表达式替换,以替换特定对应行的值,而不必逐行循环,我可以用正则表达式执行此操作吗?

给定

path: path_php
key: changeUsername
value: Te

改变

path_jamjs: C:/Users/[changeUsername]/AppData/Roaming/npm/node_modules/jamjs/bin/jam.js
path_php: C:/[changeUsername]/php/php.exe

path_jamjs: C:/Users/[changeUsername]/AppData/Roaming/npm/node_modules/jamjs/bin/jam.js
path_php: C:/Te/php/php.exe
4

1 回答 1

2
with open ("my.ini", "r") as myfile:
    my_config = myfile.read()

lines = my_config.splitlines(True)
replacements = {"path_jamjs": {"changeUsername": "Te"},
                "path_php": {"changeUsername": "TeS"}}

for path, reps in replacements.items():
    for i, line in enumerate(lines):
        if line.startswith(path + ':'):
            for key, value in reps.items():
                line = line.replace('[' + key + ']', value)
            lines[i] = line

result = ''.join(lines)
于 2013-05-09T16:15:09.780 回答