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')#保存文件