excel中文名转拼音

# 2、把金牛座.xls中的汉字人名转成用户名,写到后面的单元格中,excel在群文件
# 例如:网络-安求凤 : wl_anqiufeng
# 现场-杨帆 : xc_yangfan
# 蹭课-张哲: ck_zhangzhe
# 需求分析:
# 1、把所有人的名字从Excel取出来 xlrd
#2、把汉字转成拼音,xpinyin
#3、把xianchang、wangluo、cengkeng 替换成 xc wl ck
#4、xc-yangfang wl——anqiufeng把所有的符号替换成下划线
#5、写到原来的Excel里面 xlutius
import xpinyin,xlrd,string
from xlutils.copy import copy
book=xlrd.open_workbook(r'C:\Users\chen\Desktop\金牛座.xls')#打开文件
sheet=book.sheet_by_index(0)                #通过sheet索引获得sheet对象
p=xpinyin.Pinyin()                          #转换后存
new_book = copy(book)                       # 拷贝一份原来的excel
new_sheet = new_book.get_sheet(0)           # 获取sheet页
for i in range(1,sheet.nrows):              #循环获取每行的内容
    name=sheet.row_values(i)[0]             #获取第一列元素
    name_pinyin=p.get_pinyin(name,'')       #转成拼音
    name_pinyin=name_pinyin.replace('wangluo','wl').replace('xianchang','xc').replace('cengke','ck')
    for n in name_pinyin:                   #循环每个姓名
        if n not in string.ascii_lowercase: #判断如果不是小写字母的话,
            res=name_pinyin.replace(n,'_')  #就替换成_
            xhx_count=res.count('_')        #取下划线的个数
            if res.count('_')>1:            #判断下划线如果>1,就把多个下划线替换成一个
                res=res.replace('_'*xhx_count,'_')
    new_sheet.write(i,1,res)                #写入文件
new_book.save(r'C:\Users\chen\Desktop\金牛座.xls')#保存文件

猜你喜欢

转载自www.cnblogs.com/cwl-bj/p/9911943.html
今日推荐