[转]Python: python编码问题
这是一个我们在处理中文时, 经常遇到的问题.
python里面基本上要考虑三种编码格式
1 源文件编码
在文件头部使用coding声明。告诉python解释器该代码文件所使用的字符集。
#/usr/bin/python
#coding: utf8
2 内部编码
代码文件中的字符串,经过decode以后,被转换为统一的unicode格式的内部数据,类似于u'*'。unicode数据可以使用encode函数,再自由转换为其他格式的数据,相当于一个统一的平台。
直接输入unicode数据
>>> u'你好'
u'\u4f60\u597d'
将unicode数据转换为gb2312格式
>>> u'你好'.encode('gb2312')
'\xc4\xe3\xba\xc3'
将输入的gb2312格式的数据解码为unicode
>>> '你好'.decode('gb2312')
u'\u4f60\u597d'
输入数据的格式取决于所用shell终端的编码设置,本例中为zh_CN
[root@chenzheng python]# echo $LANG
zh_CN
解码同时转换为utf8
>>> '你好'.decode('gb2312').encode('utf8')
'\xe4\xbd\xa0\xe5\xa5\xbd'
3 外部输入的编码
其实这个和在python交互shell中输入的字符串,所遇到的情况基本一样。但程序中常常用到从网络,文件读取的数据,故此单独列出,需要特别注意其编码格式是否于系统要求相符。
下面是baidu中文本周金曲榜的链接,返回一个xml文件,编码格式为gb2312
http://box.zhangmen.baidu.com/x?op=4&listid=1
由于xml.etree.EelementTree.parse()不识别gb2312编码,在解析的时候,需要将其转换utf8格式才可以,可以使用下面的函数
def read_page(url):
"""读取gb2312编码的xml文件,转换为utf8格式"""
import urllib
udata = urllib.urlopen(url).read().decode('gb2312')
u8data = udata.encode('utf8')
return u8data.replace('gb2312', 'utf-8') #简单替换xml文件第一行的encoding属性值
另外,可以使用一个小函数来判断数据的编码格式:
def encoding(s):
cl = ['utf8', 'gb2312']
for a in cl:
try:
s.decode(a)
return a
except UnicodeEncodeError:
pass
return 'unknown'
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/jiyucn/archive/2008/02/16/2100006.aspx
相关文档:
赖勇浩(http://laiyonghao.com)
今天(2009年5月31日) OurPNP.org 搞了个聚会活动,弄了十几二十个人在广州海珠广场的堂会呆了五个小时,创下了我在 K 房呆的最长时间纪录。应他们的邀请,我做了个题为《用 python 快速搭建网游服务器》的小演讲,因为那边的电视竟然不能接电脑,所以讲的时候没有能够参照 PPT 来讲,观 ......
Python的os模块,包含了普遍的操作系统功能,这里主要学习与路径相关的函数:
os.listdir(dirname):列出dirname下的目录和文件
os.getcwd():获得当前工作目录
os.curdir:返回当前目录('.')
os.chdir(dirname):改变工作目录到dirname
os.path.isdir(name):判断name是不是一个目录,name不是目录就返回false
......
闲来无事, 玩玩python...
是采用有道翻译, 然后抓取网页的.
import re, urllib
url="http://dict.youdao.com/search?le=eng&q="
print ("input q to exit")
while 1:
word = raw_input(">>>")
if word=="q":
exit()
else:
word = word.replace(' ', '+')
url += word
u ......
8.8. queue — A synchronized queue class¶
queue -- 一个同步队列类
The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implemen ......
threading — Higher-level threading interface
This module constructs higher-level threading interfaces on top of the lower level _thread module. See also the queue module.
The dummy_threading module is provided for situations where threading cannot be used because _thread is missing.
......