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的值来判断:
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:
print c
c输出的东西看起来是乱码,那就对了,因为是utf-8的字符串。
好了,该说说codecs模块了,它和我上面说的概念是密切相关的。codecs专门用作编码转换,当然,其实通过它的接口是可以扩展到其他关于代码方面 的转换的,这个东西这里不涉及。
import codecs, sys
print ' - ' * 60
# 创建gb2312编码器
look = codecs.lookup( " gb2312 " )
# 创建utf-8编码器
look2 = codecs.lookup( " utf-8 " )
a = " 我爱北京 "
print len(a), a
# 把a编码为内部的unicode, 但为什么方法名为decode呢,我 的理解是把gb2312的字符串解码为unicode
b = 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也提供了方法.
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编码的文件试试。
------------------------------------------------------------------------------------------------------------------------------------------------------
>>> 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]
- getencoder(encoding)
- getdecoder(encoding)
- getreader(encoding)
- getwriter(encoding)
>>> encoder = codecs.getencoder("utf-8" )
>>> 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的双向服务。
完整示例代码如下:
#!/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
"""
import
codecs;
def
python_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:"
print
u
"【详解】python中的文件操作模式"
print
u
"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/
- python模块之codecs
- python模块之codecs
- Python之codecs模块
- python模块之codecs
- Python模块之codecs
- Python模块之codecs
- Python模块之codecs
- python模块之codecs: 自然语言编码转换
- python模块之codecs: 自然语言编码转换
- python模块之codecs: 自然语言编码转换
- python模块之codecs: 自然语言编码转换
- python模块之codecs: 自然语言编码转换
- python模块之codecs: 自然语言编码转换
- python模块之codecs: 自然语言编码转换
- python模块之codecs: 自然语言编码转换
- python之decode、encode及codecs模块
- python codecs模块
- Python 3的bytes/str之别 codecs模块
- QT学习资料总结
- jquery操作checkbox,实现全选。
- Gson 源码分析 总结
- IOS网络笔记--(三方库)上拉加载下拉刷新
- SNN 未被启动异常
- python模块之codecs
- 偶数个3【递推公式】
- 栈中最小元素
- Android 07:Android的国际化应用
- Java文件上传与下载
- Java—IO操作
- Linux下生产者-消费者问题的实现
- JQuery 回到顶端
- C++实现牛顿迭代法求解f(x)=0