Home > Backend Development > Python Tutorial > python2.x default encoding problem solution

python2.x default encoding problem solution

高洛峰
Release: 2017-03-21 13:17:59
Original
1616 people have browsed it

pythonProcessing Chinese in 2.x is a headache. Articles written in this area on the Internet have been unevenly tested, and there are always mistakes, so I plan to summarize an article myself.

I will also continue to modify this blog in the future study.

It is assumed that readers already have basic knowledge related to encoding. This article will not introduce it again, including what is utf-8, what is unicode, and what is the relationship between them.
str and bytecode

First of all, let’s not talk about unicode at all.

s = "人生苦短"
Copy after login

s is a string, which itself stores bytecode. So what is the format of this bytecode?

If this code is entered on the interpreter, then the format of this s is the encoding format of the interpreter. For Windows cmd, it is gbk.

If the code is saved and then executed, for example, stored as utf-8, then when the interpreter loads this program, s will be initialized to utf-8 encoding.
unicode and str

We know that unicode is an encoding standard, and the specific implementation standard may be utf-8, utf-16, gbk...

Python uses two bytes internally to store a unicode. The advantage of using unicode objects instead of str is that unicode is convenient for cross-platform.

You can define a unicode in the following two ways:

s1 = u"人生苦短"
s2 = unicode("人生苦短", "utf-8")
Copy after login

encode and decode

The encoding and decoding in python is like this:

python2.x 默认编码问题解决方法

So we can write code like this:

# -*- coding:utf-8 -*-
su = "人生苦短"
# : su是一个utf-8格式的字节串
u = s.decode("utf-8")
# : s被解码为unicode对象,赋给u
sg = u.encode("gbk")
# : u被编码为gbk格式的字节串,赋给sg
print sg
# 打印sg
Copy after login

But the reality is more complicated than this. For example, look at the following code:

s = "人生苦短"
s.encode('gbk')
Copy after login

Look! str can also be encoded (in fact, unicode objects can also be decoded, but it doesn't mean much)

Why is this possible? Looking at the arrows of the encoding process in the picture above, you can think of the principle. When encoding str, it will first decode itself into unicode using the default encoding, and then encode unicode to the encoding you specify.

This leads to the reason why most errors occur when processing Chinese in python2.x: the default encoding of python, defaultencoding is ascii

Look at this example:

# -*- coding: utf-8 -*-
s = "人生苦短"
s.encode('gbk')
Copy after login

The above code will report an error, Error message: UnicodeDecodeError: 'ascii' codec can't decode byte...

Because you did not specify defaultencoding, so it Actually doing something like this:

# -*- coding: utf-8 -*-
s = "人生苦短"
s.decode('ascii').encode('gbk')
Copy after login

Set defaultencoding

The code to set defaultencoding is as follows:

reload(sys)
sys.setdefaultencoding('utf-8')
Copy after login

If you encode and decode in python When you do not specify the encoding method, python will use defaultencoding.

For example, in the example in the previous section, if str is encoded into another format, defaultencoding will be used.

s.encode("utf-8") 等价于 s.decode(defaultencoding).encode("utf-8")
Copy after login

For another example, when you use str to create a unicode object, if you do not specify the encoding format of this str, the program will also use defaultencoding.

u = unicode("人生苦短") 等价于 u = unicode("人生苦短",defaultencoding)
Copy after login

The default defaultcoding: ascii is the cause of many errors, so setting the defaultencoding early is a good habit.

The file header declares the role of encoding.

Thanks to this blog for explaining the knowledge about the header part of python files.

The top:# -*- coding: utf-8 -*- currently seems to have three functions.

If there are Chinese comments in the code, this statement is needed
A more advanced editor (such as my emacs) will declare based on the header, Use this as the format for your code files.
The program will decode and initialize u "Life is short" through the header declaration, such a unicode object (so the storage format of the header declaration and the code must be consistent)

About requests library

requests is a very practical Python HTTP client library, which is often used when writing crawlers and testing server response data.

The Request object will return a Response object after accessing the server. This object saves the returned Http response bytecode into the content attribute.

But if you access another attribute text, a unicode object will be returned, and garbled characters will often occur here.

Because the Response object will encode the bytecode into unicode through another attribute encoding, and this encoding attribute is actually guessed by the responses themselves.

官方文档:

text
Content of the response, in unicode.

If Response.encoding is None, encoding will be guessed using chardet.

The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set r.encoding appropriately before accessing this property.

所以要么你直接使用content(字节码),要么记得把encoding设置正确,比如我获取了一段gbk编码的网页,就需要以下方法才能得到正确的unicode。

import requests
url = "http://xxx.xxx.xxx"
response = requests.get(url)
response.encoding = 'gbk'
  
print response.text
Copy after login


如果是早期的我写博客,那么我一定会写这样的例子:不仅仅要原理,更要使用方法!

如果现在的文件编码为gbk,然后文件头为:# -*- coding: utf-8 -*-,再将默认编码设置为xxx,那么如下程序的结果会是……

这就类似于,当年学c的时候,用各种优先级,结合性,指针来展示自己水平的代码。

实际上这些根本就不实用,谁会在真正的工作中写这样的代码呢?我在这里想谈谈实用的处理中文的python方法。

基本设置

主动设置defaultencoding。(默认的是ascii)

代码文件的保存格式要与文件头部的# coding:xxx一致

如果是中文,程序内部尽量使用unicode,而不用str

关于打印

你在打印str的时候,实际就是直接将字节流发送给shell。如果你的字节流编码格式与shell的编码格式不相同,就会乱码。

而你在打印unicode的时候,系统自动将其编码为shell的编码格式,是不会出现乱码的。

程序内外要统一

如果说程序内部要保证只用unicode,那么在从外部读如字节流的时候,一定要将这些字节流转化为unicode,在后面的代码中去处理unicode,而不是str。

with open("test") as f:
 for i in f:
 # 将读入的utf-8字节流进行解码
 u = i.decode('utf-8')
 ....
Copy after login

如果把连接程序内外的这段数据流比喻成通道的的话,那么与其将通道开为字节流,读入后进行解码,不如直接将通道开为unicode的。

# 使用codecs直接开unicode通道
file = codecs.open("test", "r", "utf-8")
for i in file:
 print type(i)
 # i的类型是unicode的
Copy after login

所以python处理中文编码问题的关键是你要清晰的明白,自己在干什么,打算读入什么格式的编码,声明的的这些字节是什么格式的,str到unicode是如何转换的,str的一种编码到另一种编码又是如何进行的。 还有,你不能把问题变得混乱,要自己主动去维护一种统一。

 

python 3和2很大区别就是python本身改为默认用unicode编码。

字符串不再区分"abc"和u"abc", 字符串"abc"默认就是unicode,不再代表本地编码、

由于有这种内部编码,像c#和java类似,再没有必要在语言环境内做类似设置编码,比如“sys.setdefaultencoding”;

也因此也python 3的代码和包管理上打破了和2.x的兼容。2.x的扩展包要适应这种情况改写。

另一个问题是语言环境内只有unicode怎么输出gbk之类的本地编码。


1.如果你在Python中进行编码和解码的时候,不指定编码方式,那么python就会使用defaultencoding。 而python2.x的的defaultencoding是ascii,

这也就是大多数python编码报错:“UnicodeDecodeError: 'ascii' codec can't decode byte ......”的原因。

 

2.关于头部的# coding:utf-8,有以下几个作用 2.1如果代码中有中文注释,就需要此声明 2.2比较高级的编辑器(比如我的emacs),会根据头部声明,将此作为代码文件的格式。 2.3程序会通过头部声明,解码初始化 u"人生苦短",这样的unicode对象,(所以头部声明和代码的存储格式要一致)

python2.7以后不用setdefaultencoding了,这两个是没有区别的


这两个作用不一样, 1. # coding:utf-8 作用是定义源代码的编码. 如果没有定义, 此源码中是不可以包含中文字符串的. PEP 0263 -- Defining Python Source Code Encodings https://www.python.org/dev/peps/pep-0263/ 2. sys.getdefaultencoding() 是设置默认的string的编码格式

答按惯例都在(序列化)输出时才转换成本地编码。

The above is the detailed content of python2.x default encoding problem solution. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template