Python 正则表达式:用匹配的dict条目替换文本变量和括号中的数字 我想用一个函数替换C++源代码文件中的数组变量。 此外,我需要用枚举替换硬编码的数字。 为此,我想使用正则表达式和dict。dict表示枚举关联的数字
这是我想用python脚本转换的示例代码:Python 正则表达式:用匹配的dict条目替换文本变量和括号中的数字 我想用一个函数替换C++源代码文件中的数组变量。 此外,我需要用枚举替换硬编码的数字。 为此,我想使用正则表达式和dict。dict表示枚举关联的数字,python,regex,Python,Regex,这是我想用python脚本转换的示例代码: int a = foo[0]; int b = foo[1]; int c = foo[2]; 这是转换后的预期结果: int a = bar(enum_zero); int b = bar(enum_one); int c = bar(enum_two); 用于枚举替换的Python字典: enums = dict([('zero',0), ('one', 1), ('two', 2)])
int a = foo[0];
int b = foo[1];
int c = foo[2];
这是转换后的预期结果:
int a = bar(enum_zero);
int b = bar(enum_one);
int c = bar(enum_two);
用于枚举替换的Python字典:
enums = dict([('zero',0),
('one', 1),
('two', 2)])
这是当前非工作状态,可以用函数替换数组,但不能用枚举替换数字:
import fileinput
import re
enums = dict([('zero',0),
('one', 1),
('two', 2)])
search = r'foo'
replace = r'bar'
read = open('test.cpp', 'r')
write = open('out.cpp', 'w')
for line in read:
if line.find(search) != -1:
s_tag = r'(\-)('+search+r')\[(\d+)\](?=\.\w+)'
r_tag = r'\1'+replace+r'(\3)'
line = re.sub(s_tag, r_tag, line, re.M)
write.write(line)
else:
write.write(line)
read.close()
如果您更改字典并使用groups(),可能会简化工作:
如果您更改字典并使用groups(),可能会简化工作:
这一切都可以使用一个
re.sub()
调用来完成,如下所示:
import re
search = r'foo'
replace = r'bar'
s_tag = r'\b(' + search + r') *?\[ *?(\d+) *?\]'
enums = {'0':'enum_zero', '1':'enum_one', '2':'enum_two'}
with open('test.cpp') as f_cpp:
text = f_cpp.read()
with open('out.cpp', 'w') as f_out:
f_out.write(re.sub(s_tag, lambda x: "{}({})".format(replace, enums[x.group(2)]), text))
为您提供以下内容的输出文件:
int a = bar(enum_zero);
int b = bar(enum_one);
int c = bar(enum_two);
它使用lambda函数使用enums
字典查找所需的替换,并将输出格式化为合适的函数调用格式
将
与
一起使用也意味着以后无需显式关闭文件。这一切都可以通过一个re.sub()
调用来完成,如下所示:
import re
search = r'foo'
replace = r'bar'
s_tag = r'\b(' + search + r') *?\[ *?(\d+) *?\]'
enums = {'0':'enum_zero', '1':'enum_one', '2':'enum_two'}
with open('test.cpp') as f_cpp:
text = f_cpp.read()
with open('out.cpp', 'w') as f_out:
f_out.write(re.sub(s_tag, lambda x: "{}({})".format(replace, enums[x.group(2)]), text))
为您提供以下内容的输出文件:
int a = bar(enum_zero);
int b = bar(enum_one);
int c = bar(enum_two);
它使用lambda函数使用enums
字典查找所需的替换,并将输出格式化为合适的函数调用格式
将与
一起使用也意味着以后无需显式关闭文件。我想将“示例代码”转换为“所需代码”我想将“示例代码”转换为“所需代码”