如何用Python修改dict_ex.py文件中含类实例的字典值?
修改包含类实例的Python字典文件的方案
核心思路
直接解析并修改Python代码的抽象语法树(AST),避免手动字符串替换的风险,同时保留原文件的类实例初始化格式,不会引入额外序列化标记。
步骤与代码实现
1. 确认类定义文件
确保dict_class.py中的类结构正确,示例如下:
# dict_class.py class linear: def __init__(self, a, b): self.a = a self.b = b class quadratic: def __init__(self, a, b, c): self.a = a self.b = b self.c = c
2. 编写修改脚本
创建modify_dict.py,使用ast模块解析、修改代码:
import ast import astunparse def modify_example_dict(file_path): # 读取原文件内容 with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # 解析为抽象语法树 tree = ast.parse(content) # 定位example_dict的赋值节点 for node in ast.walk(tree): if isinstance(node, ast.Assign) and len(node.targets) == 1: target = node.targets[0] if isinstance(target, ast.Name) and target.id == 'example_dict': dict_node = node.value # 遍历字典键值对,修改目标参数 for idx, key_val in enumerate(dict_node.keys): # 修改ex1的b参数 if isinstance(key_val, ast.Constant) and key_val.value == "ex1": list_node = dict_node.values[idx] linear_node = list_node.elements[0] for kw in linear_node.keywords: if kw.arg == 'b': kw.value = ast.Constant(value=5.0) # 修改ex2的c参数 if isinstance(key_val, ast.Constant) and key_val.value == "ex2": list_node = dict_node.values[idx] quadratic_node = list_node.elements[0] for kw in quadratic_node.keywords: if kw.arg == 'c': kw.value = ast.Constant(value=10.0) # 将修改后的AST转换为代码文本并写入文件 modified_code = astunparse.unparse(tree) with open(file_path, 'w', encoding='utf-8') as f: f.write(modified_code) # 执行修改 modify_example_dict('dict_ex.py')
3. 依赖与注意事项
- 安装依赖库:
pip install astunparse(Python3.9标准库的ast.unparse功能有限,astunparse兼容性更好) - 该方法会保留原文件的代码结构和换行格式,不会破坏原有代码风格
- 如需新增键值对或类实例,只需在AST中创建对应节点即可
简单场景替代方案
如果文件格式固定,可使用正则表达式快速修改(仅适用于格式无变化的场景):
import re def simple_modify(file_path): with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # 替换ex1的b参数值 content = re.sub(r'linear\(a=1.0,\s*b=2.0\)', r'linear(a=1.0,\n b=5.0)', content) # 替换ex2的c参数值 content = re.sub(r'quadratic\(a=1.0,\s*b=2.0,\s*c=3.0\)', r'quadratic(a=1.0,\n b=2.0,\n c=10.0)', content) with open(file_path, 'w', encoding='utf-8') as f: f.write(content) simple_modify('dict_ex.py')
注意:正则方案对代码格式敏感度高,若参数值、换行或注释有变化,容易匹配失败
内容的提问来源于stack exchange,提问作者hjl43
相关产品推荐
相关产品推荐

