1.由于文件的名字有可能重复的原因,重命名后,有的文件名已存在,为了保持数据的统一性,重命名异常时删除重复数据。
2.路径问题建议使用
- os.path.join()
代码如下:
# coding:utf-8
import os, re
from pypinyin import lazy_pinyin
import pypinyin
from string import digits
# 姓氏文件路径
path = r'D:\PythonFiles\\addPinyinPackage\nameFile\stringToPinyin'
path2= path
slash = '\\'
# 姓氏的文件名重名,重名命名成拼音的字符串
def chineseRenamePinyinName():
fileList = os.listdir(path)
attribute = '.wav'
for name in fileList:
nameStr = name.strip().split('.')[0].strip()
nameStr = filterNumbersInStrings(nameStr)
fileName = nameStr + attribute
oldFile = os.path.join(path + slash, name)
newFile = os.path.join(path2 + slash, fileName)
try:
os.rename(oldFile, newFile)
except:
if os.path.exists(oldFile):
os.remove(oldFile)
# 生成姓名的拼音
def filterNumbersInStrings(name):
textList = []
for text in name:
name_pinyin2 = lazy_pinyin(text, style=pypinyin.TONE3)
remove_digits = str.maketrans('', '', digits)
res = name_pinyin2[0].translate(remove_digits)
textList.append(res)
return '_'.join(textList)
if __name__ == '__main__':
chineseRenamePinyinName()
网友评论