python 编码格式

来源:互联网 发布:淘宝怎么管理店铺 编辑:程序博客网 时间:2024/06/03 21:42

学习总结一下自己碰到的python编码问题

1:文件是UTF-8,内容有中文

  • 直接打印中文
    这里写图片描述这里写图片描述
  • 结果:提示Non-ASCII
  • 原因:因为python 源码文件默认的编码是ASCII,识别不了中文(两个字符)
  • 解决方案: 在文件的开始【第一行或第二行】加入指定的能识别 Non-ASCII字符 的编码格式

2:直接控制台cmd打印中文

这里写图片描述
- 结果:打印出的中文乱码
- 原因:这是因为zh使用utf8编码的,而到win cmd中的编码格式是 GB2312:936【可以通过chcp查看当前cmd编码格式】,输入是用utf8格式 , 输出用 GB2312 ,从而导致出错!
解决方案:zh = u’此处是中文’,这样做的目的就是将zh变成了unicode字符串。那么输出到cmd时就会encode(‘gb2312’),就可以正常显示了

3:写入文件出错

这里写图片描述
- 结果:写入文件提示EncodeError。
- 原因:zh此刻从用utf8编码的字符串成了 unicode字符串,unicode 是中间编码,打印到cmd会将unicode->gb2312,所以打印到cmd不会乱码;但是f.write()出现乱码,是因为zh是unicode,但是用python 本身的ASCII码来识别,超出了0-127,python识别不了。

4. 写文件成功

这里写图片描述
- 结果:写入文件成功!
- 原因: The encoding information is then used by the Python parser to interpret the file using the given encoding,也就是说指定了编码格式。。 除了coding:utf8之外,还有设置defaultencoding(‘utf8’)。

5.读取网页(requests)

  • 5.1 response.text() :response.encoding = ‘utf8’
    这里写图片描述
    • 结果:写入文件中文不乱码
  • 5.2 response.text() :response.encoding = ‘ISO-8859-1’
    这里写图片描述
    • 结果:写入中文乱码

总结:

  • 1 coding:utf8 保证源文件能存在中文
  • 2 reload(sys),sys.seddefaultencoding(‘utf8’) 是设置python默认编码格式,即字符串等都用utf8编码
  • 3 unicode是中间码,是编码格式转换的中间桥梁。如果unicode编码的字符串输出到IDE,那么可以正常显示;例如字符串是utf8,而IDE是gbk,那么输出到IDE需要decode为unicode。
  • 4 requests返回response对象 需要查看一下几个编码格式:

    # print response.headers['content-type']# print response.encoding# print '11',response.text# header = response.headers# print response.apparent_encoding# print requests.utils.get_encodings_from_content(response.content)# print type(response.text.decode(response.content))
  • 5 如果response.encoding=’ISO-8859-1’,那么需要设置为utf8

  • 6 如果response.encoding=gbk等其他编码,那么直接decode()就可以了。
原创粉丝点击