python中文转拼音

来源:互联网 发布:51单片机蓝牙小车程序 编辑:程序博客网 时间:2024/05/21 17:39


本文参照的:

pip install xpinyin 

http://blog.csdn.net/hanchaohao2012/article/details/70183976


还有这个可以用:

https://github.com/mozillazg/python-pinyin


参考:http://www.crazyant.net/1789.html

#!/usr/bin/env python# -*- coding:utf-8 -*-"""install xpinyinpip install xpinyin"""from xpinyin import Pinyinimport osimport syspinyin_converter = Pinyin()def gci(filepath):#遍历filepath下所有文件,包括子目录    files = os.listdir(filepath)    for fi in files:        fi_d = os.path.join(filepath,fi)        if os.path.isdir(fi_d):            gci(fi_d)        else:            res = pinyin_converter.get_pinyin(fi, '_')            res = remove_chars(res, '-', '(', ')', '(', ')')            res = res.replace(' ', '_')            res = res.lower()            if res[-5] == '_':                res = res[:-5] + res[-4:]            src_path = filepath + '\\' + fi            dest_path = filepath + '\\' + res            print(src_path + '->' + res)            if not os._exists(dest_path):             os.rename(src_path, dest_path)    dirpath= os.path.dirname(filepath)    dirname=os.path.basename(filepath)    res = pinyin_converter.get_pinyin(dirname, '_')    res = remove_chars(res, '-', '(', ')', '(', ')')    res = res.replace(' ', '_')    res = res.lower()    if len(res)>5:        if res[-5] == '_':            res = res[:-5] + res[-4:]    src_path = filepath    dest_path= os.path.join( dirpath , res)    print(src_path + '->' + res)    if not os.path.isdir(dest_path):        os.rename(src_path, dest_path)def list_all(dir_name):    for dirpath, dirnames, filenames in os.walk(dir_name):        for filename in filenames:            res = pinyin_converter.get_pinyin(filename, '_')            res = remove_chars(res, '-', '(', ')', '(', ')')            res = res.replace(' ', '_')            res = res.lower()            if res[-5] == '_':                res = res[:-5] + res[-4:]            src_path = dirpath + '\\' + filename            dest_path = dirpath + '\\' + res            print(src_path + '->' + res)            os.rename(src_path, dest_path)        for filename in dirnames:            res = pinyin_converter.get_pinyin(filename, '_')            res = remove_chars(res, '-', '(', ')', '(', ')')            res = res.replace(' ', '_')            res = res.lower()            if res[-5] == '_':                res = res[:-5] + res[-4:]            src_path = dirpath + '\\' + filename            dest_path = dirpath + '\\' + res            print(src_path + '->' + res)            os.rename(src_path, dest_path)def remove_chars(filename, *chars):    for i in range(len(chars)):        filename = filename.replace(chars[i], '')    return filenameif __name__ == '__main__':    # list_all(r"E:\baiduwangpan\pic")    # 递归遍历/root目录下所有文件    gci(r"E:\baiduwangpan\pic")    # print(sys.argv)    # if len(sys.argv) == 1:    #     print('must has name dir')    #     exit(-1)    # for dir_name in sys.argv[1:]:    #     list_all(dir_name)

原创粉丝点击