最新消息:

在Python程序中使用汉字等非ASCII编码字符—Python编码问题整理

Python admin 2961浏览 0评论

一、几个概念性东西

1、  ASCII:
标准的 ASCII 编码只使用7个比特来表示一个字符,因此最多编码128个字符。扩充的 ASCII 使用8个比特来表示一个字符,最多也只能编码 256 个字符。

2、UNICODE:
使用2个甚至4个字节来编码一个字符,因此可以将世界上所有的字符进行统一编码。

3、UTF:
UNICODE编码转换格式,就是用来指导如何将 unicode 编码成适合文件存储和网络传输的字节序列的形式 (unicode ->
str)。像其他的一些编码方式 gb2312, gb18030, big5 和 UTF 的作用是一样的,只是编码方式不同。

总结:utf-8是unicode的一种实现方式,unicode、gbk、gb2312是编码字符集;

Python 里面有两种数据模型来支持字符串这种数据类型,一种是 str,另外一种是 unicode ,它们都是 basestring 的派生类型,这个可以参考 Python Language Ref 中的描述: Strings :The items of a string are characters. There is no separate character type; a character is represented by a string of one item. Characters represent (at least) 8-bit bytes. The built-in functions chr() and ord() convert between characters and nonnegative integers  representing the byte values. Bytes with the values 0-127 usually represent the corresponding ASCII values, but the interpretation of values is up to the program. The string data type is also used to  represent arrays of bytes, e.g., to hold data read from a file.  (On systems whose native character set is not ASCII, strings may use EBCDIC in their internal representation, provided the functions chr() and ord() implement a mapping between ASCII and EBCDIC, and string comparison preserves the ASCII order. Or perhaps someone can propose a better rule?)

Unicode :
The items of a Unicode object are Unicode code units. A Unicode code unit is represented by a Unicode object of one item and can hold either a 16-bit or 32-bit value representing a Unicode ordinal (the maximum value for the ordinal is given in sys.maxunicode, and depends on how Python is configured at compile time). Surrogate pairs may be present in the Unicode object, and will be reported as two separate items. The built-in functions unichr() and ord() convert between code units and nonnegative integers representing the Unicode ordinals as defined in the Unicode Standard 3.0. Conversion from and to other encodings are possible through the Unicode method encode() and the built-in function unicode().

这里面是这么几句: “The items of a string are characters”, “The items of a Unicode object are Unicode code units”, “The string data type is also used to represent arrays of bytes, e.g., to hold data read from a file.” 一二句说明 str 和 unicode 的组成单元(item)是什么(因为它们同是 sequence ) 。sequence 默认的 __len__ 函数的返回值正是该序列组成单元的个数。这样的话,len(‘abcd’) == 4 和 len(u’我是中文’) == 4 就很 容易理解了。 第三句告诉我们像从文件输入输出的时候是用 str 来表示数据的数组。不止是文件操作,我想在网络传输的时候应该也是这样的。这就是为什么一个 unicode 字符串在写入文件或者在网络上传输的时候要进行编码的原因了。

 

Python 里面的编码和解码也就是 unicode 和 str 这两种形式的相互转化。编码是 unicode -> str(即encoded string),相反的,解码就是 str(encoded string) -> unicode。 下面剩下的问题就是确定何时需要进行编码或者解码了,像一些库是 unicode 版的,这样我们在将这些库函数的返回值进行传输或者写入文件的时候就要考虑将它编码成合适的类型。

二、 Python编码中的重要问题

一、 关于文件开头的”编码指示”,也就是 # -*- coding: -*- 或#coding=utf-8这个语句,当然其他编码方式如gbk/gb2312也可以。Python 默认脚本文件都是 ANSCII 编码的,当文件中有非 ANSCII 编码范围内的字符的时候就要使用”编码指示”来修正。

二、关于 sys.defaultencoding,这个在解码没有明确指明解码方式的时候使用,即没有明确指明解码方式时,就使用sys.setdefaultencoding指明的编码方式进行解码。如:

#! /usr/bin/env python 
# -*- coding: utf-8 -*- 

s = '中文'  # 注意这里的 s 是 str 类型(utf8格式)的,而不是 unicode 类型
s.encode('gbk')

上面代码将 s 重新编码为 gbk 的格式,即进行 unicode -> str 的转换。因为 s 本身就是 str 类型(utf-8格式的str)的,因此 Python 会自动的先将 s 解码为 unicode ,然后再编码成 gbk。因为解码是python自动进行的,我们没有指明解码方式,python 就会使用 sys.defaultencoding 指明的方式来解码。很多情况下 sys.defaultencoding 是 ANSCII,如果 s 不是这个类型就会出错。
拿上面的情况来说,我的 sys.defaultencoding 是 anscii,而 s 的编码方式和文件的编码方式一致,是 utf8 的,所
以出错了: UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe4 in position 0: ordinal not in range(128)
对于这种情况,我们有两种方法来改正错误:
一是明确的指示出 s 的编码方式 :

#! /usr/bin/env python 
# -*- coding: utf-8 -*- 

s = '中文' 
s.decode('utf-8').encode('gbk')

二是更改 sys.defaultencoding 为文件的编码方式.

#! /usr/bin/env python 
# -*- coding: utf-8 -*- 

import sys 
reload(sys) # Python2.5 初始化后会删除 sys.setdefaultencoding 这个方法,我们需要重新载入 
sys.setdefaultencoding('utf-8') 

str = '中文' 
str.encode('gbk')

三、编解码相关函数介绍

1、 unicode(string [, encoding[, errors]]) -> object
介绍:Create a new Unicode object from the given encoded string. encoding defaults to the current default string encoding.errors can be ‘strict’, ‘replace’ or ‘ignore’ and defaults to ‘strict’.

2、encode(…)
S.encode([encoding[,errors]]) -> string or unicode

Encodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with  codecs.register_error that can handle UnicodeEncodeErrors.

3、 decode(…)
S.decode([encoding[,errors]]) -> string or unicode

Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is ‘strict’ meaning that encoding errors raise a UnicodeDecodeError. Other possible values are ‘ignore’ and ‘replace’ as well as any other name registerd with codecs.register_error that is able to handle UnicodeDecodeErrors.

总结:使用unicode()或decode()函数将str转换为unicode.使用encode()将unicode类型转换为str类型。 可以使用encode()函数来将一种方式的编码字符串转换成另一种编码方式(使用的是默认编码方式进行解码,通过setdefaultencoding 进行设置)。

 

四、print函数

python 中的print原理:When Python executes a print statement, it simply passes the output to the operating system (using fwrite() or something like it), and some other program is responsible for actually displaying that output on the screen. For example, on Windows, it might be the Windows console subsystem that displays the result. Or if you’re using Windows and running Python on a Unix box somewhere else, your Windows SSH client is actually responsible for displaying the data. If you are running Python in an xterm on Unix, then xterm and your X server handle the display.
To print data reliably, you must know the encoding that this display program expects.
简单地说,python中的print直接把字符串传递给操作系统,所以你需要把str解码成与操作系统一致的格式。Windows使用CP936(几乎与gbk相同),所以也可以使用gbk。即最后打印时转换成gb2312或gbk等格式。

#! /usr/bin/env python
# coding=utf-8
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
s="中文"
s_gbk=s.encode("gbk")
print s_gbk

参考:http://my.oschina.net/yixiusztx/blog/68114

转载请注明:jinglingshu的博客 » 在Python程序中使用汉字等非ASCII编码字符—Python编码问题整理

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址