我有一个文本文件("input.param"
),它用作包的输入文件。我需要修改一个参数的值。需要更改的行如下:
param1 0.01
model_name run_param1
我需要搜索参数param1
并为一系列不同的值修改0.01
的值,同时model_name
也将针对不同的{{1 }}。例如,如果param1
更改为0.03,则para1
更改为'run_param1_p03'。以下是我的一些尝试代码:
model_name
但是,这不起作用。我猜主要的问题是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
或param1
并更改其值。
答案 0 :(得分:1)
我正在编辑此答案,以便更准确地回答原始问题,而这个问题并没有足够解决。
问题是“ replace
命令无法识别空格” 。为此,re
(或正则表达式)模块可能会很有帮助。您的文档由一个条目及其值组成,并用空格分隔:
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
是任何非空格字符,或者('\t', ' ', '\r', '\n')
中的任何 not
+
表示一个或多个为贪婪搜索(将继续搜索,直到模式停止匹配为止)
\s+
是 any 空格字符(与\S
相反,请注意此处的情况)
()
表示分组,或您希望对搜索分组的方式
如果您愿意的话,这些组使您很容易将参数分解为变量。要将其应用于您已经拥有的代码:
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.ljust
和str.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
,但可以将其排除在外。