Python 通过参数名称修改文本文件

Python modify text file by the name of arguments

我有一个文本文件 ("input.param"),它用作包的输入文件。我需要修改一个参数的值。需要更改的行如下:

param1        0.01
model_name    run_param1

我需要搜索参数 param1 并修改 0.01 的值以获得一系列不同的值,同时 model_name 也会根据 [ 的不同值进行相应更改=14=]。例如,如果 para1 更改为 0.03,则 model_name 更改为 'run_param1_p03'。下面是我的一些尝试代码:

import numpy as np
import os


param1_range = np.arange(0.01,0.5,0.01)
with open('input.param', 'r') as file :
   filedata = file.read()

for p_value in param1_range:
    filedata.replace('param1        0.01', 'param1        ' + str(p_value))
    filedata.replace('model_name    run_param1', 'model_name    run_param1' + '_p0' + str(int(round(p_value*100))))

   with open('input.param', 'w') as file:
       file.write(filedata)

   os.system('./bin/run_app param/input.param')

但是,这不起作用。我猜主要问题是 replace 命令无法识别 space。但我不知道如何搜索参数 param1model_name 并更改它们的值。

我正在编辑此答案以更准确地回答原始问题,但它做得不够。

问题是"The replace command can not recognize the space"。为了做到这一点,re 或 regex 模块可以提供很大的帮助。您的文档由一个条目及其值组成,由 spaces:

分隔
param1        0.01
model_name    run_param1

在正则表达式中,一般捕获如下所示:

import re

someline = 'param1        0.01'
pattern = re.match(r'^(\S+)\s+(\S+)$', someline)

pattern.groups()
# ('param1', '0.01')

正则表达式函数如下:

^ 捕获行首 \S任何 非 space 字符,或者 ('\t', ' ', '\r', '\n') 的任何字符 +表示一个或多个为贪心搜索(会一直往前直到模式停止匹配) \s+any whitespace 字符(与 [=17= 相反,注意这里的大小写) () 指明分组,或者您希望如何对搜索进行分组

如果您愿意,这些组使您可以相当容易地将参数解压缩到变量中。要将其应用于您已有的代码:

import numpy as np 
import re

param1_range = np.arange(0.01,0.5,0.01)
filedata = []

with open('input.param', 'r') as file:
    # This will put the lines in a list
    # so you can use ^ and $ in the regex
    for line in file:
        filedata.append(line.strip()) # get rid of trailing newlines

# filedata now looks like:
# ['param1        0.01', 'model_name    run_param1']

# It might be easier to use a dictionary to keep all of your param vals
# since you aren't changing the names, just the values
groups = [re.match('^(\S+)\s+(\S+)$', x).groups() for x in filedata]

# Now you have a list of tuples which can be fed to dict()
my_params = dict(groups)
# {'param1': '0.01', 'model_name': 'run_param1'}

# Now just use that dict for setting your params
for p_value in param1_range:
    my_params['param1'] = str(p_value)
    my_params['model_name'] = 'run_param1_p0' + str(int(round(p_value*100)))

    # And for the formatting back into the file, you can do some quick padding to get the format you want
    with open('somefile.param', 'w') as fh:
        content = '\n'.join([k.ljust(20) + v.rjust(20) for k,v in my_params.items()])
        fh.write(content)

填充是使用 str.ljuststr.rjust 方法完成的,因此您得到的格式如下所示:

for k, v in dict(groups).items():
    intstr = k.ljust(20) + v.rjust(20)
    print(intstr)

param1                              0.01
model_name                    run_param1

如果您愿意,可以说可以省略 rjust