首页 > 代码库 > Python脚本自动提取和替换代码中的中文
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])
Python脚本自动提取和替换代码中的中文
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。