python模块之codecs

来源:互联网 发布:linux内核调试方法 编辑:程序博客网 时间:2024/04/30 18:54

python对多国语言的处理是支持的很好的,它可以处理现在任意编码的字符,这里深入的研究一下python对多种不同语言的处理。
    有一点需要清楚的是,当python要做编码转换的时候,会借助于内部的编码,转换过程是这样的:
        原有编码 -> 内部编码 -> 目的编码 
    python的内部是使用unicode来处理的,但是unicode的使用需要考虑的是它的编码格式有两种,一是UCS-2,它一共有65536个码 位,另一种是UCS-4,它有2147483648g个码位。对于这两种格式,python都是支持的,这个是在编译时通过--enable- unicode=ucs2或--enable-unicode=ucs4来指定的。那么我们自己默认安装的python有的什么编码怎么来确定呢?有一个 办法,就是通过sys.maxunicode的值来判断:

 import  sys
 
print  sys.maxunicode


    如果输出的值为65535,那么就是UCS-2,如果输出是1114111就是UCS-4编码。
我们要认识到一点:当一个字符串转换为内部编码后,它就不是str类型了!它是unicode类型:

  =   " 风卷残云 " 
 
print  type(a)
 b 
 =  a.unicode(a,  " gb2312 " )
 
print  type(b)


输出:
<type 'str'>
<type 'unicode'>

这个时候b可以方便的任意转换为其他编码,比如转换为utf-8:

  =  b.encode( " utf-8 " )
 
print  c


c输出的东西看起来是乱码,那就对了,因为是utf-8的字符串。
    好了,该说说codecs模块了,它和我上面说的概念是密切相关的。codecs专门用作编码转换,当然,其实通过它的接口是可以扩展到其他关于代码方面 的转换的,这个东西这里不涉及。

# -*- encoding: gb2312 -*- 
import  codecs, sys

print   ' - ' * 60 
#  创建gb2312编码器 
look   =  codecs.lookup( " gb2312 " )
#  创建utf-8编码器 
look2  =  codecs.lookup( " utf-8 " )

 =   " 我爱北京 " 

print  len(a), a
#  把a编码为内部的unicode, 但为什么方法名为decode呢,我 的理解是把gb2312的字符串解码为unicode 
 =  look.decode(a)
#  返回的b[0]是数据,b[1]是长度,这个时候的类型是unicode 了 
print  b[ 1 ], b[0], type(b[0])
#  把内部编码的unicode转换为gb2312编码的字符 串,encode方法会返回一个字符串类型 
b2  =  look.encode(b[0])
#  发现不一样的地方了吧?转换回来之后,字符串长度由14变为了7! 现在 的返回的长度才是真正的字数,原来的是字节数 
print  b2[ 1 ], b2[0], type(b2[0])
#  虽然上面返回了字数,但并不意味着用len求b2[0]的长度就是7了, 仍然还是14,仅仅是codecs.encode会统计字数 
print  len(b2[0])


    上面的代码就是codecs的使用,是最常见的用法。另外还有一个问题就是,如果我们处理的文件里的字符编码是其他类型的呢?这个读取进行做处理也需要特 殊的处理的。codecs也提供了方法.

 # -*- encoding: gb2312 -*- 
 
import  codecs, sys
 
 
#  用codecs提供的open方法来指定打开的文件的语言编码,它会在读 取的时候自动转换为内部unicode 
 
bfile  =  codecs.open( " dddd.txt "  ' r '  " big5 " )
 
# bfile = open("dddd.txt", 'r') 
 

 ss 
 =  bfile.read()
 bfile.close()
 
#  输出,这个时候看到的就是转换后的结果。如果使用语言内建的open函数 来打开文件,这里看到的必定是乱码 
 
print  ss, type(ss)


上面这个处理big5的,可以去找段big5编码的文件试试。

 

------------------------------------------------------------------------------------------------------------------------------------------------------




字符的编码是按照某种规则在单字节字符和多字节字符之间进行转换的某种方法。从单字节到多字节叫做decoding,从多字节到单字节叫做 encoding。在这些规则中经常用到的无非是UTF-8和GB2312两种。
 
在Python中,codecs模块提供了实现这些规则的方法,通过模块公开的方法我们能够方便地获取某种编码方式的Encoder和 Decoder工厂函数(Factory function),以及StreamReader、StreamWriter和StreamReaderWriter类。
 
使用“import codecs”导入codecs模块。
 
codecs模块中重要的函数之一是lookup,它只有一个参数encoding,指的是编码方式的名称,即utf-8或者gb2312等 等。如下示例:
>>> import codecs
>>> t = codecs.lookup("utf-8" )
>>> print t
(<built-in function utf_8_encode>, <function decode at 0x00AA25B0>, <class encodings.utf_8.StreamReader at 0x00AA0720>, <class encodings.utf_8.StreamWriter at 0x00AA06F0>) 
>>> encoder = t[0]
>>> decoder = t[1]
>>> StreamReader = t[2]
>>> StreamWriter = t[3]
lookup函数返回一个包含四个元素的TUPLE,其中t[0]是encoder的函数引用,t[1]是decoder的函数引用,t[2] 是UTF-8编码方式的StreamReader类对象引用,t[3]是UTF-8编码方式的StreamWriter类对象引用相信对Python熟悉 的你肯定知道接下来该怎么用它们了。
 
codecs模块还提供了方便程序员使用的单独函数,以简化对lookup的调用。它们是:
  • getencoder(encoding)
  • getdecoder(encoding)
  • getreader(encoding)
  • getwriter(encoding)
如果我们只是想获取一种utf-8编码的encoder方法,那么只需要这样做:
>>> encoder = codecs.getencoder("utf-8" )
 
另外,对于StreamReader和StreamWriter的简化, codecs模块提供一个open方法。相对于built-in对象File的open方法,前者多了三个参数encoding, errors, buffering。这三个参数都是可选参数,但是对于应用来说,需要明确指定encoding的值,而errors和buffering使用默认值即 可。使用方法如下:
>>> fin = codecs.open("e://mycomputer.txt" , "r" , "utf-8" )
>>> print fin.readline()
这是我的电脑 
>>> fin.close()
 

总结一下,codecs模块为我们解决的字符编码的处理提供了lookup方法,它接受一个字符编码名称的参数,并返回指定字符编码对应的 encoder、decoder、StreamReader和StreamWriter的函数对象和类对象的引用。为了简化对lookup方法的调用, codecs还提供了getencoder(encoding)、getdecoder(encoding)、getreader(encoding)和 getwriter(encoding)方法;进一步,简化对特定字符编码的StreamReader、StreamWriter和 StreamReaderWriter的访问,codecs更直接地提供了open方法,通过encoding参数传递字符编码名称,即可获得对 encoder和decoder的双向服务。


完整示例代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【教程】用Python的codecs处理各种字符编码的字符串和文件
http://www.crifan.com/tutorial_python_codecs_process_file_char_encoding
  
Author:     Crifan Li
Version:    2013-10-20
Contact:   http://www.crifan.com/about/me
"""
 
importcodecs;
 
defpython_codecs_demo():
    """demo how to use codecs to handle file with specific encoding"""
    testStrUnicode=u"中文测试Unicode字符串";
    print"testStrUnicode=",testStrUnicode
    testStrUtf8=testStrUnicode.encode("UTF-8");
    testStrGbk=testStrUnicode.encode("GBK");
 
    outputFilename="outputFile.txt"
 
    print"------------ 1.UTF-8 write and read ------------"
    print"--- (1) write UTF-8 string into file ---"
    # 'a+': read,write,append
    # 'w' : clear before, then write
    outputFp=codecs.open(outputFilename,'w');
    outputFp.write(testStrUtf8);
    outputFp.flush();
    outputFp.close();
    print"--- (2) read out previously written UTF-8 content ---"
    readoutFp=codecs.open(outputFilename,'r','UTF-8');
    #here already is unicode, for we have pass "UTF-8" to codecs.open
    readOutStrUnicodeFromUtf8=readoutFp.read()
    readoutFp.close();
    print"readOutStrUnicodeFromUtf8=",readOutStrUnicodeFromUtf8
 
    print"------------ 2.GBK write and read ------------"
    print"--- (1) write GBK string into file ---"
    # 'a+': read,write,append
    # 'w' : clear before, then write
    outputFp=codecs.open(outputFilename,'w');
    outputFp.write(testStrGbk);
    outputFp.flush();
    outputFp.close();
    print"--- (2) read out previously written GBK content ---"
    readoutFp=codecs.open(outputFilename,'r','GBK');
    #here already is unicode, for we have pass "GBK" to codecs.open
    readOutStrUnicodeFromGbk=readoutFp.read()
    readoutFp.close();
    print"readOutStrUnicodeFromGbk=",readOutStrUnicodeFromGbk
 
    print"Note: "
    print"1. more about encoding, please refer:"
    printu"【详解】python中的文件操作模式"
    printu"http://www.crifan.com/summary_python_file_operation_mode/"
 
if__name__ =="__main__":
    python_codecs_demo()

输出为:

E:\dev_root\python\tutorial_summary\python_codecs_demo>python_codecs_demo.py

testStrUnicode= 中文测试Unicode字符串

———— 1.UTF-8 write and read ————

— (1) write UTF-8 string into file —

— ()2) read out previously written UTF-8 content —

readOutStrUnicodeFromUtf8= 中文测试Unicode字符串

———— 2.GBK write and read ————

— (1) write GBK string into file —

— (2) read out previously written GBK content —

readOutStrUnicodeFromGbk= 中文测试Unicode字符串

Note:

1. more about encoding, please refer:

【详解】python中的文件操作模式

http://www.crifan.com/summary_python_file_operation_mode/


0 0