Table of Contents
如何处理中文编码的问题
如何判断字符str的编码是什么?
总结
Home Backend Development Python Tutorial Summary of Chinese encoding issues in python

Summary of Chinese encoding issues in python

Apr 14, 2018 pm 02:31 PM
python Chinese encoding

本篇文章给大家分享的内容是总结关于python中的中文编码问题,有着一定的参考价值,有需要的朋友可以参考一下

如何处理中文编码的问题

python的UnicodeDecodeError: ‘utf8’ codec can’t decode byte 0xxx in position
这个错误是因为你代码中的某个字符串使用了费ascii编码的字符,也就是它代表的16进制的编码超过127。
解决这个问题可以使用下面的方法解决,其实就是设置默认的编码。python 2.x的默认编码是ascii,如果改为utf-8,就可以了。

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

其实从python 3.0以后默认就用utf-8,就没有这个问题了。

新手写pyhton程序经常遇到编码问题,其实是对py的编码不熟悉,经常范小毛病,郁闷好久。。。
今天终于搞懂的py的编码。
1. pyhton的所有内置库、方法接受的是unicode编码的字符串。
2. str.decode 函数就是转成unicode编码,所以能decode的字符串传级python的内置库、函数都能正确运行。
3.问题在于这个decode函数解码时到底要传哪个参数:utf-8,gbk,gb2312……等N种编码。参数不当,就会抛类似异常:
UnicodeDecodeError: ‘gbk’ codec can’t decode bytes in position 2-3: illegal multibyte sequence
UnicodeDecodeError: ‘utf8’ codec can’t decode bytes in position 0-1: invalid data
下面举个例子:

#coding:utf-8    
#指定本文件编码为utf8  
import os  
# 以下为示例代码,不一定能运行。随意写的,无编译运行过。  
# 例子以XP平台为例,因为linux平台编码(UTF-8)与window平台(GBK)不一样。  
# 假设D盘下面有很多中文名称文件  
filelist = os.listdir(r"d:\\") # 此处返回的list中的中文是以GBK编码的,你可以通过查看cmd窗口属性看到。  
for path in filelist:  
    if os.path.isdir(path): continue  
     fp = open(path.decode("GBK") , 'rb')  # 如果此处用 path.decode("UTF-8") 就会抛异常,原因是wind的dir命令返回的是GBK编码  
    print len(fp.read())  
     fp.close()  
filepath =r"d:\\中文文件.doc"             # 假设此文存在,记得要带中文  
fp = open(filepath.decode('utf-8'), "rb") #这里使用utf8参数进行解码,原因是文件头里有句coding: utf-8  print len(fp.read())  
fp.close()  
path2 = u"d:\\中文文件.doc"  # 假如这里有个u在前面,这个变量就是unicode编码了,不用解码。  
fp = open(path2, 'rb')  
print len(fp.read())  
fp.close()
Copy after login

为什么Python使用过程中会出现各式各样的乱码问题,明明是中文字符却显示成“\xe4\xb8\xad\xe6\x96\x87”的形式?
为什么会报错“UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not in range(128)”?本文就来研究一下这个问题。
字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。
decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode(‘gb2312’),表示将gb2312编码的字符串str1转换成unicode编码。
encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode(‘gb2312’),表示将unicode编码的字符串str2转换成gb2312编码。
因此,转码的时候一定要先搞明白,字符串str是什么编码,然后decode成unicode,然后再encode成其他编码
代码中字符串的默认编码与代码文件本身的编码一致。
如:s=’中文’
如果是在utf8的文件中,该字符串就是utf8编码,如果是在gb2312的文件中,则其编码为gb2312。这种情况下,要进行编码转换,都需要先用decode方法将其转换成unicode编码,再使用encode方法将其转换成其他编码。通常,在没有指定特定的编码方式时,都是使用的系统默认编码创建的代码文件。
如果字符串是这样定义:s=u’中文’
则该字符串的编码就被指定为unicode了,即python的内部编码,而与代码文件本身的编码无关。因此,对于这种情况做编码转换,只需要直接使用encode方法将其转换成指定编码即可。
如果一个字符串已经是unicode了,再进行解码则将出错,因此通常要对其编码方式是否为unicode进行判断:
isinstance(s, unicode) #用来判断是否为unicode
用非unicode编码形式的str来encode会报错
如何获得系统的默认编码?

#!/usr/bin/env python
#coding=utf-8
import sys
print sys.getdefaultencoding()
Copy after login

该段程序在英文WindowsXP上输出为:ascii
在某些IDE中,字符串的输出总是出现乱码,甚至错误,其实是由于IDE的结果输出控制台自身不能显示字符串的编码,而不是程序本身的问题。
如在UliPad中运行如下代码:

s=u"中文"print s
Copy after login

会提示:UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not in range(128)。这是因为UliPad在英文WindowsXP上的控制台信息输出窗口是按照ascii编码输出的(英文系统的默认编码是ascii),而上面代码中的字符串是Unicode编码的,所以输出时产生了错误。
将最后一句改为:

print s.encode('gb2312')
Copy after login

则能正确输出“中文”两个字。
若最后一句改为:

print s.encode('utf8')
Copy after login

则输出:\xe4\xb8\xad\xe6\x96\x87,这是控制台信息输出窗口按照ascii编码输出utf8编码的字符串的结果。
unicode(str,’gb2312’)与str.decode(‘gb2312’)是一样的,都是将gb2312编码的str转为unicode编码
使用str.class可以查看str的编码形式
原理说了半天,最后来个包治百病的吧:)

#!/usr/bin/env python 
#coding=utf-8 
s="中文" 

if isinstance(s, unicode): 
#s=u"中文" 
print s.encode('gb2312') 
else: 
#s="中文" 
print s.decode('utf-8').encode('gb2312')
Copy after login

如何判断字符str的编码是什么?

使用 chardet 可以很方便的实现字符串/文件的编码检测。尤其是中文网页,有的页面使用GBK/GB2312,有的使用UTF8,如果你需要去爬一些页面,知道网页编码很重要的,虽然HTML页面有charset标签,但是有些时候是不对的。那么chardet就能帮我们大忙了。

chardet实例

 import urllib
 rawdata = urllib.urlopen('http://www.google.cn/').read() 
 import chardet
 chardet.detect(rawdata)
{'confidence': 0.98999999999999999, 'encoding': 'GB2312'}
Copy after login

chardet可以直接用detect函数来检测所给字符的编码。函数返回值为字典,有2个元数,一个是检测的可信度,另外一个就是检测到的编码。

chardet 安装

下载chardet后,解压chardet压缩包,直接将chardet文件夹放在应用程序目录下,就可以使用import chardet开始使用chardet了。

或者使用setup.py安装文件,将chardet拷贝到Python系统目录下,这样你所有的python程序只要用import chardet就可以了。

python setup.py install
Copy after login

总结

尽量把所有的input 都decode成unicode。即 str.decode(‘utf-8’);

输出时,再encode成所需的编码格式

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode(‘gb2312’),表示将gb2312编码的字符串str1转换成unicode编码。
encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode(‘gb2312’),表示将unicode编码的字符串str2转换成gb2312编码。

相关推荐:

也谈 Python 的中文编码处理

PYTHON-进阶-编码处理小结

Python中文编码与Unicode

判断字符的编码

The above is the detailed content of Summary of Chinese encoding issues in python. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

How to train PyTorch model on CentOS How to train PyTorch model on CentOS Apr 14, 2025 pm 03:03 PM

Efficient training of PyTorch models on CentOS systems requires steps, and this article will provide detailed guides. 1. Environment preparation: Python and dependency installation: CentOS system usually preinstalls Python, but the version may be older. It is recommended to use yum or dnf to install Python 3 and upgrade pip: sudoyumupdatepython3 (or sudodnfupdatepython3), pip3install--upgradepip. CUDA and cuDNN (GPU acceleration): If you use NVIDIAGPU, you need to install CUDATool

How is the GPU support for PyTorch on CentOS How is the GPU support for PyTorch on CentOS Apr 14, 2025 pm 06:48 PM

Enable PyTorch GPU acceleration on CentOS system requires the installation of CUDA, cuDNN and GPU versions of PyTorch. The following steps will guide you through the process: CUDA and cuDNN installation determine CUDA version compatibility: Use the nvidia-smi command to view the CUDA version supported by your NVIDIA graphics card. For example, your MX450 graphics card may support CUDA11.1 or higher. Download and install CUDAToolkit: Visit the official website of NVIDIACUDAToolkit and download and install the corresponding version according to the highest CUDA version supported by your graphics card. Install cuDNN library:

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

How to choose the PyTorch version under CentOS How to choose the PyTorch version under CentOS Apr 14, 2025 pm 02:51 PM

When selecting a PyTorch version under CentOS, the following key factors need to be considered: 1. CUDA version compatibility GPU support: If you have NVIDIA GPU and want to utilize GPU acceleration, you need to choose PyTorch that supports the corresponding CUDA version. You can view the CUDA version supported by running the nvidia-smi command. CPU version: If you don't have a GPU or don't want to use a GPU, you can choose a CPU version of PyTorch. 2. Python version PyTorch

MiniOpen Centos compatibility MiniOpen Centos compatibility Apr 14, 2025 pm 05:45 PM

MinIO Object Storage: High-performance deployment under CentOS system MinIO is a high-performance, distributed object storage system developed based on the Go language, compatible with AmazonS3. It supports a variety of client languages, including Java, Python, JavaScript, and Go. This article will briefly introduce the installation and compatibility of MinIO on CentOS systems. CentOS version compatibility MinIO has been verified on multiple CentOS versions, including but not limited to: CentOS7.9: Provides a complete installation guide covering cluster configuration, environment preparation, configuration file settings, disk partitioning, and MinI

How to operate distributed training of PyTorch on CentOS How to operate distributed training of PyTorch on CentOS Apr 14, 2025 pm 06:36 PM

PyTorch distributed training on CentOS system requires the following steps: PyTorch installation: The premise is that Python and pip are installed in CentOS system. Depending on your CUDA version, get the appropriate installation command from the PyTorch official website. For CPU-only training, you can use the following command: pipinstalltorchtorchvisiontorchaudio If you need GPU support, make sure that the corresponding version of CUDA and cuDNN are installed and use the corresponding PyTorch version for installation. Distributed environment configuration: Distributed training usually requires multiple machines or single-machine multiple GPUs. Place

See all articles