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

python2.x default encoding problem solution

Mar 21, 2017 pm 01:17 PM
python

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

See all articles