我有一个C文件,其中包含以下两行:
(*Something_something_XXXName_1()) = 3.54324E+7;
(*Something_something_XXXName_2()) = 7.13123E+7;
当我运行我的脚本(稍后会出现)时,我想用新值替换它,例如:
(*Something_something_XXXName_1()) = 1.53493E+7;
(*Something_something_XXXName_2()) = 9.12839E+7;
现在到我的python脚本
我提供了一个ID
ID_File = "anId" #imagine the ID looking like x00...
extracted_id, formated_for_cfile, x = func_name(ID_File)
在这里,我将值更改为另一个。
for c_file in args.cpath:
f = open(c_file, 'r')
c_contents = f.read()
c_replaced_contents = re.sub(r'(.*)Something_something_XXXName_{0}\(\)\) = '.format(x+1) +
'.*;(.*)', r'\Something_something_XXXName_{0}()) = '.format(x+1) +
formated_for_cfile + r';\2', c_contents)
f.close()
with open(c_file, 'w') as c_write:
c_write.write(c_replaced_contents)
此函数获取ID并将其拆分为两个值。你可以看到它也做了两件事。从part_str到part_intstr =获取转换为字符串的普通int值。从str_formated_for_cfile到formated_for_cfile,我得到1.53493E + 7和9.12839E + 7
def func_name(ID):
str_id = ID_File[1:17]
a_str_id = ''
for x in range(0, 2):
part_str = str_id[8 * x:8 * (x + 1)]
part_int = int(part_str, 16)
part_intstr = str(part_int)
str_formated_for_cfile = '{:.7E}'.format(part_int).replace("E+0", "E+")
formated_for_cfile = re.sub(r'(.*)0+E(.*)', r'\1E\2',str_formated_for_cfile)
a_str_id = a_str_id.lstrip() + " " + part_intstr
extracted_id = list(a_str_id.split(' '))
return extracted_id, formated_for_cfile, x
问题是没有替换我的C文件中的行。我错过了什么?
以下是代码彼此相邻的脚本(仅为了更简单的可读性):
ID_File = "anId" #imagine the ID looking like x00...
extracted_id, formated_for_cfile, x = func_name(ID_File)
for c_file in args.cpath:
f = open(c_file, 'r')
c_contents = f.read()
c_replaced_contents = re.sub(r'(.*)Something_something_XXXName_{0}\(\)\) = '.format(x+1) +
'.*;(.*)', r'\Something_something_XXXName_{0}()) = '.format(x+1) +
formated_for_cfile + r';\2', c_contents)
f.close()
with open(c_file, 'w') as c_write:
c_write.write(c_replaced_contents)
def func_name(ID):
str_id = ID_File[1:17]
a_str_id = ''
for x in range(0, 2):
part_str = str_id[8 * x:8 * (x + 1)]
part_int = int(part_str, 16)
part_intstr = str(part_int)
str_formated_for_cfile = '{:.7E}'.format(part_int).replace("E+0", "E+")
formated_for_cfile = re.sub(r'(.*)0+E(.*)', r'\1E\2',str_formated_for_cfile)
a_str_id = a_str_id.lstrip() + " " + part_intstr
extracted_id = list(a_str_id.split(' '))
return extracted_id, formated_for_cfile, x
答案 0 :(得分:0)
使用sed
sed s/'(*Something_something_XXXName_1())'/'(*Something_something_XXXName_1())=1.53493E+7;\/\/'/g file.c >new_file.c
OR
#define NEW_VAL 1.53493E+7
sed s/'(*Something_something_XXXName_1())'/'(*Something_something_XXXName_1())=NEW_VALUE;\/\/'/g file.c >new_file.c
答案 1 :(得分:0)
你的正则表达式有问题。
在第一个参数中,您有Something_something_XXXName_{0}
,但这与Something_something_XXXName_1
不匹配。相反,它应该是Something_something_XXXName_\d
或Something_something_XXXName_(\d+)
。在第二个参数中,\S
表示匹配任何非空白字符,您可能需要\1S
。