import os # 目录定义 ROOT_DIR = r"./" EXTRA_FILES = [ "./TransPyC.py", "./StubGen.py", "./Projectrans.py" ] def snake_to_upper_camel(s: str) -> str: if not s: return s if s.startswith('_'): first = '_' rest = s[1:] else: first = '' rest = s parts = rest.split('_') pascal = ''.join(part.capitalize() for part in parts) return first + pascal while True: old_str = input("请输入原蛇形字符串:").strip() new_input = input("替换内容(留空自动转大驼峰):").strip() if not old_str: print("错误:原字符串不能为空\n") continue total_mod = 0 # ====================== 1. 处理 lib 下所有 .py ====================== for root, _, files in os.walk(ROOT_DIR): for file in files: if file.endswith(".py"): file_path = os.path.join(root, file) try: with open(file_path, "r", encoding="utf-8") as f: content = f.read() if new_input == "": replace_target = snake_to_upper_camel(old_str) new_content = content.replace(old_str, replace_target) else: new_content = content.replace(old_str, new_input) if new_content != content: with open(file_path, "w", encoding="utf-8") as f: f.write(new_content) print(f"已修改:{file_path}") total_mod += 1 except Exception as err: print(f"异常 {file_path}:{err}") # ====================== 2. 处理根目录下 3 个指定文件 ====================== for file_path in EXTRA_FILES: if os.path.exists(file_path): try: with open(file_path, "r", encoding="utf-8") as f: content = f.read() if new_input == "": replace_target = snake_to_upper_camel(old_str) new_content = content.replace(old_str, replace_target) else: new_content = content.replace(old_str, new_input) if new_content != content: with open(file_path, "w", encoding="utf-8") as f: f.write(new_content) print(f"已修改:{file_path}") total_mod += 1 except Exception as err: print(f"异常 {file_path}:{err}") print(f"\n处理完成,共计修改 {total_mod} 个文件\n")