Python脚本自动提取和替换代码中的中文
# -*- coding: utf-8 -*- import os import os.path import re import sys reload(sys) sys.setdefaultencoding( "utf-8" ) root_path = os.getcwd()+ os.sep list_name = "" str_list = [] # full path def check_file(file): dic = os.path.splitext(file) file_n = os.path.split(file) if dic[1] == ".lua" and file_n[1] != "Language.lua": return True return False def is_file(path): return os.path.isfile(path) def replace(match): if re.search(u'[\u4e00-\u9fa5]+', match.group(0)) != None: global list_name if match.group(0) in str_list: return "Util" + list_name+".str"+str(str_list.index(match.group(0))) else: str_list.append(match.group(0)) return "Util" + list_name+".str"+str(len(str_list)-1) else: return match.group(0) def replace_china(path): lua_file = open(path) file_content = lua_file.read() # lua中tabel的名字 global list_name, str_list str_list = [] list_name = os.path.split(path)[1][:-4].upper() try: utf_content = file_content.decode("utf8") except: print path return re_str=u'"(.*?)"' pattern = re.compile(re_str) results = pattern.sub(replace, utf_content) if results != utf_content: #写入文件 write_file(path, results) create_tabel(path) def write_file(path, replace_str): lua_file = open(path, "w") lua_file.write(replace_str) lua_file.close() # 创建lua中的tabel def create_tabel(path): global list_name lua_tabel = open("common\utils\Language.lua", "a") lua_tabel.write("\n") lua_tabel.write("Util" + list_name + " = {\n") for index, china_str in enumerate(str_list): lua_tabel.write(" str" + str(index) + " = " + china_str + ",\n") lua_tabel.write("}") lua_tabel.close() def walk_dir(): for root, dir_names, file_names in os.walk(root_path): for file_name in file_names: full_path = os.path.join(root, file_name) if is_file(full_path): if check_file(full_path): replace_china(full_path) else: walk_dir(full_path) if __name__ == "__main__": walk_dir() # replace_china(sys.argv[1])
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业