Python openpyxl 将 Excel中的汉字 转换成拼音首字母

将Excel中的汉字列,转换成拼音首字母,并保存

需要安装导入  pypinyin、openpyxl 库

# pip install pypinyin
from pypinyin import lazy_pinyin, Style
import openpyxl


def py(str_data):
    """
       获取字符串的首字母
       :param str_data: 字符串
       :return: 返回首字母缩写(大写)
       """
    p = ''.join(lazy_pinyin(str_data, style=Style.FIRST_LETTER))
    return p.upper()
    # return 首字母缩写[:-4].upper()  # 不要倒数后四位,去掉有限公司


def read_excel():
    file = "D:\\Temp\\Test.xlsx"
    # 打开excel
    excel = openpyxl.load_workbook(file)
    # 使用指定工作表
    # sheet = excel.active  # 当前激活的工作表
    sheet = excel.get_sheet_by_name('Sheet1')

    # 读取标题行
    for row in sheet.iter_rows(max_row=1):
        title_row = [cell.value for cell in row]
    print(title_row)
    # 读取指定列的数据 将第5列的汉字转成拼音后,存放到第6列中
    for col in sheet.iter_cols(min_row=1, min_col=5, max_row=None, max_col=5):
        col_value = [row.value for row in col]
        for idx, cv in enumerate(col):
            if str(cv.value) == 'None':
                # 跳过空值
                continue
            sheet.cell(row=idx + 1, column=6, value=py(cv.value))
            print('%s %s %s' % (idx, cv.value, str(cv.value) == 'None'))
    excel.save(file)
    excel.close()
    print(col_value)


if __name__ == "__main__":
    read_excel()
    # print(py("WPF 在类型为  的对象上找不到 command 属性"))
    print('done')

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章