美文网首页
python 中文编码问题

python 中文编码问题

作者: 是风车大渣渣啊 | 来源:发表于2019-06-19 15:22 被阅读0次

被一个中文编码的 error 卡了好久,师兄给我的从mac拿过来的含有中文的txt文档。文件首部含有 BOM 字符!记录以自省…

  • 最早的版本是这样,
with open('input/out_classes.txt', 'r', encoding='utf-8') as cf:
    for line in cf:
        label = line.strip('\r\n')
        label_list.append((label))
        print(label)
  • 报错是这样:

UnicodeEncodeError: 'gbk' codec can't encode character '\ufeff' in position 0

The Unicode character U+FEFF is the byte order mark, or BOM, and is used to tell the difference between big- and little-endian UTF-16 encoding. If you decode the web page using the right codec, Python will remove it for you.

#!python2
#coding: utf8
u = u'ABC'
e8 = u.encode('utf-8')        # encode without BOM
e8s = u.encode('utf-8-sig')   # encode with BOM
e16 = u.encode('utf-16')      # encode with BOM
e16le = u.encode('utf-16le')  # encode without BOM
e16be = u.encode('utf-16be')  # encode without BOM
print 'utf-8     %r' % e8
print 'utf-8-sig %r' % e8s
print 'utf-16    %r' % e16
print 'utf-16le  %r' % e16le
print 'utf-16be  %r' % e16be
print
print 'utf-8  w/ BOM decoded with utf-8     %r' % e8s.decode('utf-8')
print 'utf-8  w/ BOM decoded with utf-8-sig %r' % e8s.decode('utf-8-sig')
print 'utf-16 w/ BOM decoded with utf-16    %r' % e16.decode('utf-16')
print 'utf-16 w/ BOM decoded with utf-16le  %r' % e16.decode('utf-16le')
  • 最后改成这样:
with open('input/out_classes.txt', 'r', encoding='utf-8-sig') as cf:
    for line in cf:
        label = line.strip('\r\n')
        label_list.append((label))
        print(label)

相关文章

  • python 字符串前加u

    python中文编码问题,字符串前面加u

  • Python2和python3的区别

    1.python2的中文编码问题 python2是用ASCII码作为默认编码,因此在项目代码中如果出现中文是会报错...

  • python中文编码问题

    python2.7.13 (1)如果需要输出中文,则需要在文件开头输入 # coding:utf-8 或 # -*...

  • python 中文编码问题

    被一个中文编码的 error 卡了好久,师兄给我的从mac拿过来的含有中文的txt文档。文件首部含有 BOM 字符...

  • GB2312/GBK/Big5

    python中爬取网页是总是遇到中文编码问题总结如下; 1.如何判断一段文字(网页)的编码格式2.中文编码的种类和...

  • 文本/数据操作

    大文件读取 json 中文编码问题: 排序: url中文转码(python3) csv 文件操作模式 xml lx...

  • Python 接口测试练习(天气预报)

    利用网上现成的的接口,用python练习了下(又碰到了中文编码问题了:获取的页面源码 编码就是整不成中文) 天气查...

  • Python教程导航

    Python 教程 Python 简介 Python 环境搭建 Python 中文编码 Python 基础语法 ...

  • 将utf-8编码的csv文件转换为gb2312编码的csv文件

    csv文件编码转换:解决utf-8编码的文件在excel打开时中文乱码问题。 Python完整代码如下: # -*...

  • Python设定系统默认编码

    Python系统默认编码是ascii,有中文时会有问题,需要修改默认编码为utf-8,方法如下: 代码中修改编码,...

网友评论

      本文标题:python 中文编码问题

      本文链接:https://www.haomeiwen.com/subject/jxdkqctx.html