zoukankan      html  css  js  c++  java
  • Python读取 csv文件中文乱码处理

    需求:
    按行解析读取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]
  • 相关阅读:
    BZOJ 3626: [LNOI2014]LCA(树链剖分+离线处理)
    python备用
    STL的使用。。备忘
    DP专题
    任务
    hdu 网络流题集
    hdu KM匹配题集
    hdu 差分约束题集
    hdu 2sat题集
    Codeforces Round #261 (Div. 2)
  • 原文地址:https://www.cnblogs.com/dozn/p/8668201.html
Copyright © 2011-2022 走看看