Python中将旧式字符串格式化转换为Flask-Babel支持的format格式
解决方案
1. 核心转换函数
下面的Python函数可以将单个旧式%格式化语句转换为str.format()格式,完全匹配你需要的转换规则:
import re def convert_percent_format(old_statement): # 匹配完整的%格式化语句结构:字符串 + % + (参数元组) pattern = r'\'(.*?)\'\s*%\s*\(\s*(.*?)\s*\)' match = re.fullmatch(pattern, old_statement.strip()) if not match: return old_statement # 不匹配则返回原内容 raw_str, raw_args = match.groups() # 提取字符串中的所有占位符(%.2f、%s等) placeholder_matches = list(re.finditer(r'%(\.\d+f|s)', raw_str)) # 拆分参数列表 args_list = [arg.strip() for arg in raw_args.split(',')] # 从参数中提取变量名(处理float(Var)或直接Var的情况) var_names = [] for arg in args_list: var_match = re.match(r'(?:\w+\()?(\w+)\)?', arg) var_names.append(var_match.group(1) if var_match else arg) # 替换字符串中的占位符为{变量名} converted_str = raw_str for ph, var in zip(placeholder_matches, var_names): converted_str = converted_str.replace(ph.group(0), f'{{{var}}}') # 构建format的关键字参数 format_args = ', '.join([f'{var}={arg}' for var, arg in zip(var_names, args_list)]) # 拼接最终语句 return f"'{converted_str}'.format({format_args})"
2. 测试示例
用你提供的输入测试:
old_str = "'Interest Rate <b>%.2f</b> of <b>%.2f</b> can not change to <b>%s</b> of new loan product <b>%s</b>.'%(float(OldInterestRate),float(NewInterestRate),LoanProductOldDescription,LoanProductNewDescription)" print(convert_percent_format(old_str))
输出结果完全符合你的需求:
'Interest Rate <b>{OldInterestRate}</b> of <b>{NewInterestRate}</b> can not change to <b>{LoanProductOldDescription}</b> of new loan product <b>{LoanProductNewDescription}</b>.'.format(OldInterestRate=float(OldInterestRate),NewInterestRate=float(NewInterestRate),LoanProductOldDescription=LoanProductOldDescription,LoanProductNewDescription=LoanProductNewDescription)
3. 批量处理文件
如果需要批量转换目录下的所有Python文件,使用以下代码(务必先备份文件):
import os def batch_convert(root_directory): for dirpath, _, filenames in os.walk(root_directory): for filename in filenames: if filename.endswith('.py'): file_path = os.path.join(dirpath, filename) # 读取文件内容 with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # 替换所有匹配的%格式化语句 def replace_callback(match): return convert_percent_format(match.group(0)) updated_content = re.sub(r'\'(.*?)\'\s*%\s*\(\s*(.*?)\s*\)', replace_callback, content) # 写回文件 with open(file_path, 'w', encoding='utf-8') as f: f.write(updated_content) print(f"已处理:{file_path}") # 使用示例:替换指定目录下的所有.py文件 # batch_convert('/path/to/your/project')
注意事项
- 备份优先:批量处理前一定要备份所有文件,避免转换错误导致代码丢失
- 兼容性:当前函数支持
%.2f、%s占位符,如果有其他类型(如%d),可以修改正则中的占位符匹配规则为%(\.\d+f|s|d) - 复杂场景:如果参数包含嵌套括号或复杂表达式,需要调整变量名提取的正则规则,当前版本适配你提供的典型场景
内容的提问来源于stack exchange,提问作者Houy Narun
相关产品推荐
相关产品推荐

