python模块之codecs
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类型:
a
=
"
风卷残云
"
print
type(a)
b
=
a.unicode(a,
"
gb2312
"
)
print
type(b)
输出:
<type 'str'>
<type 'unicode'>
这个时候b可以方便的任意转换为其他编码,比如转换为utf-8:
c
=
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
"
)
a
=
"
我爱北京
"
print
len(a), a
#
把a编码为内部的unicode, 但为什么方法名为decode呢,我
的理解是把gb2312的字符串解码为unicode
b
=
look.de
相关文档:
前言:
最近又想学习python,又想去温习一下算法,于是就想出了这个两不误的方法,^_^
堆栈:
使用python的列表结构,详情可以查看help(list)
#Filename: stack.py
shoplist=['apple','mango','carrot','banana']
shoplist.append('rice')
popitem=shoplist[-1]
del shoplist[-1]
print 'the popitem is',popitem
......
英文版Dive in python可以在下面找到中文翻译http://linuxtoy.org/docs/dip/toc/index.html
模块的__name__,当模块被import时,其为模块的名字,当模块作为main执行的时候,其为__main__
词典的key是大小写敏感的。
List也支持重载+操作,用于将两个list连接起来,并返回一个List,因此它没有extended执行高效。list也+ ......
refer from: http://www.daniweb.com/forums/thread115282.html#
python
Syntax
(Toggle Plain Text
)
# respond to a key
without the need to press
enter
import
Tkinter
as tk
def
keypress(
event)
:
if
event.keysym
== 'Escape'
:
root.destroy
......
ubuntu10.05出来了这两天一直在折腾,显示wubi无反应,然后从硬盘安装期间又遇到grub错误等问题。安装成功后搞个中文输入法就老半天,最后使用Pinyin这个还算好用,有点想搜狗就是没什么词库。最恶心的还是vim的问题,用apt-get install vim装的vim不支持系统剪切板,只好从源代码编译,可是我尝试了很多次总是没有python支 ......
当我们这样建立文件时
f =
file('x1.txt', 'w')
f.write(u'中文')
f.colse()
直
接结果应该是类似
f.write(u'中文')
UnicodeEncodeError: 'ascii'
codec can't encode characters in position 0-16: ordinal not in
range(128)
要直接写 utf-8 文件怎么办呢?
import codecs
f = codecs. ......