需求:
按行解析讀取csv文件存入關係型數據庫——主要是中文字體解析;
遇到的問題:
直接解析出來的數據爲list形式,並且編碼格式爲unicode;
解決問題:
前提了解:
中文編碼的規則 —— GB2312
字符串在Python內部的表示是unicode編碼,在作編碼轉換時,一般須要以unicode做爲中間編碼,即先將其餘編碼的字符串解碼(decode)成unicode,再從unicode編碼(encode)成另外一種編碼。數據庫
decode的做用是將其餘編碼的字符串轉換成unicode編碼,如str1.decode(‘gb2312’),表示將gb2312編碼的字符串轉換成unicode編碼。字體
encode的做用是將unicode編碼轉換成其餘編碼的字符串,如str2.encode(‘gb2312’),表示將unicode編碼的字符串轉換成gb2312編碼。編碼
示例以下:
filepath:文件絕對路徑
with open(filepath, mode='rb') as f:
reader = csv.reader(f)
# i 設置按行獲取數據
for i, rows in enumerate(reader):
try:
# 解決讀取csv文件中文格式亂碼——gb2312只支持普通中文字符
row1 = [row1.decode('GB2312').encode('utf-8') for row1 in rows]
except:
#存在繁體時
#gbk支持繁體中文和日文假文
row1 = [row1.decode('GBK').encode('utf-8') for row1 in rows]