随笔 - 6  文章 - 0  评论 - 3  阅读 - 9184

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])
复制代码

 

posted on   二二的路人甲  阅读(1572)  评论(0编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示