码迷,mamicode.com
首页 > 编程语言 > 详细

Python脚本自动提取和替换代码中的中文

时间:2017-01-10 14:30:16      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:ace   code   div   import   pre   global   for   except   etc   

 # -*- 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脚本自动提取和替换代码中的中文

标签:ace   code   div   import   pre   global   for   except   etc   

原文地址:http://www.cnblogs.com/eedlrj/p/6269076.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!