1. 程式人生 > >python excel 繁體轉換

python excel 繁體轉換

username sql import master 提交 pen brush num pass

#下載2個文件
https://raw.githubusercontent.com/skydark/nstools/master/zhtools/langconv.py 
https://raw.githubusercontent.com/skydark/nstools/master/zhtools/zh_wiki.py
import xlrd
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from langconv import *
def readExcel(path):
    workBook = xlrd.open_workbook(path)
    names = workBook.sheet_names()
    print(‘excel的所有表名‘, names)
    # 根據索引獲取當前表
    firstSheet = workBook.sheet_by_index(0)  # 獲取第一張表
    print(‘當前的sheet名稱: %s‘ % firstSheet.name)
    print(‘當前表的總行數: %s‘ % firstSheet.nrows)
    print(‘當前表占用的列數: %s‘ % firstSheet.ncols)

    # 獲取第一行的value
    # firstRow = firstSheet.row_values(0)
    # print(‘表第一行(列名稱): %s‘ % firstRow)
    for num in range(firstSheet.nrows):
        if num > 0:
            rows = firstSheet.row_values(num)
            for index, value in enumerate(rows):
                if index == 1:
                    if str(value) and len(str(value)) == 8:
                        yield str(value), rows[2]
                        continue


ret = readExcel("C:/Users/kaige/Desktop/四元玉鑒/新商品備案-稅則號/照陸方稅號(2018對照表 配合臺方稅則調整).xls")


# 繁體轉簡體
def Traditional2Simplified(sentence):
    ‘‘‘
    將sentence中的繁體字轉為簡體字
    ‘‘‘
    sentence = Converter(‘zh-hans‘).convert(sentence)
    return sentence
# 數據連接引擎
engine = create_engine(‘mssql+pymssql://username:password/dbname?charset=utf8‘, echo=False)
# orm 映射實體類
metadata_r = MetaData()
metadata_r.reflect(engine, only=[‘Base_CustTax_copy1_2‘])
Base_r = automap_base(metadata=metadata_r)
Base_r.prepare()
Base_CustTax_copy1_2 = Base_r.classes.Base_CustTax_copy1_2
# 獲取session實例
session = Session(engine)
for code, name in ret:
    # 添加對象
    base = Base_CustTax_copy1_2(Cust_Code=code,Cmdt_Desc=Traditional2Simplified(name))
    session.add(base)
# 提交
session.commit()


# 繁體轉簡體
def Simplified2Traditional(sentence):
    ‘‘‘
    將sentence中的簡體字轉為繁體字
    ‘‘‘
    sentence = Converter(‘zh-hant‘).convert(sentence)
    return sentence

  

原文: 傳送門

python excel 繁體轉換