1. 程式人生 > >Python 批量修改 漢語轉拼音

Python 批量修改 漢語轉拼音

如果看過我上一篇部落格的人可能會記得我之前進行批量處理圖片大小的經歷,就在那之後,經過一系列的步驟之後,我們終於得到了夢寐以求的Bundle包,只可惜是中文的,500多個包啊。全部是中文的。但是Unity對於中文路徑的資源是 可以 寫 不可以 讀。所以需要改成對應的拼音,(如果有高手大哥可以轉換成英文的話,可以給我留言哦,謝謝),下面就是我的python指令碼了,修改資料夾下以“.unity3d”為字尾的所有檔案的中文名-》拼音名字;

備註:

2.匯入了send2trash庫,同樣是刪除不需要的檔案到垃圾箱內(就是unity的配置檔案.meta檔案啦)

# -*- coding: gb18030 -*-   
import sys, os, glob
from pypinyin import pinyin, lazy_pinyin
import pypinyin
from send2trash import send2trash

reload(sys)
sys.setdefaultencoding('utf-8')

rename_postfix=".unity3d"
delete_postfix=".meta"

def Py_Log(_string):
    print "----"+_string.decode('utf-8')+"----"

def rename_file(file_path):
    mPath, ext = os.path.splitext(file_path)

    if(ext==rename_postfix):
        ch_name=get_ch_name(mPath)
        if(has_chinese(ch_name)):
            py_name=get_py_name(ch_name);
            print "名字轉換:   "+unicode(ch_name,'gbk')+"   ==>   "+py_name
            names = os.path.split(file_path)
            new_path = names[0]+"\\"+py_name+rename_postfix
            if (os.path.exists(new_path)):
                print "\""+py_name+"\"檔案已經存在請修改後重試"
                raw_input('press enter key to continue')
            else:
                os.rename(file_path,new_path)
    elif(ext==delete_postfix):
        send2trash(file_path)
        print "Delete "+delete_postfix+" file :"+file_path

def has_chinese(text):
    hz_yes = False
    for ch in unicode(text,"gbk"):
        if ch >= u'\u4e00' and ch<=u'\u9fa5':
            hz_yes=True
        else:
            continue
    return hz_yes

def get_ch_name(mPath):
    tmp = mPath.split('\\')
    ch_name=tmp[len(tmp)-1]
    ch_name=ch_name.strip('0123456789')
    return ch_name

def get_py_name(ch_name):
    queue=""
    py_name=lazy_pinyin(unicode(ch_name,'gbk'))
    
    for pn in py_name:
        queue+=pn.capitalize()
    return queue

def BFS_Dir(dirPath, dirCallback = None, fileCallback = None):
    queue = []
    ret = []
    queue.append(dirPath);
    while len(queue) > 0:
        tmp = queue.pop(0)
        if(os.path.isdir(tmp)):
            ret.append(tmp)
            for item in os.listdir(tmp):
                queue.append(os.path.join(tmp, item))
            if dirCallback:
                dirCallback(tmp)
        elif(os.path.isfile(tmp)):
            ret.append(tmp)
            if fileCallback:
                fileCallback(tmp)
    return ret

def printDir(dirPath):
    print "dir: " + dirPath

def printFile(dirPath):
    print "file: " + dirPath
    rename_file(dirPath)

if __name__ == '__main__':
    while True:
        path = raw_input("Path:")
        try:
            b = BFS_Dir(path , printDir, printFile)
            Py_Log ("\r\n          **********\r\n"+"*********檔案處理完畢*********"+"\r\n          **********\r\n")
        except:
            print "Unexpected error:", sys.exc_info()
        raw_input('press enter key to exit')