免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 9009 | 回复: 0
打印 上一主题 下一主题

python编码问题解决 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-05-04 15:45 |只看该作者 |倒序浏览

转载:Python、Unicode和中文
python的中文问题一直是困扰新手的头疼问题,这篇文章将给你详细地讲解一下这方面的知识。当然,几乎可以确定的是,在将来的版本中,python会彻底解决此问题,不用我们这么麻烦了。
先来看看python的版本:
>>> import sys
>>> sys.version
'2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]'
(一)
用记事本创建一个文件ChineseTest.py,默认ANSI:
s = "中文"
print s
测试一下瞧瞧:
E:\Project\Python\Test>python ChineseTest.py
  File "ChineseTest.py", line 1
SyntaxError: Non-ASCII character '\xd6' in file ChineseTest.py on line 1, but no encoding declared; see
http://www.pytho
n.org/peps/pep-0263.html for details
偷偷地把文件编码改成UTF-8:
E:\Project\Python\Test>python ChineseTest.py
  File "ChineseTest.py", line 1
SyntaxError: Non-ASCII character '\xe4' in file ChineseTest.py on line 1, but no encoding declared; see
http://www.pytho
n.org/peps/pep-0263.html for details
无济于事。。。
既然它提供了网址,那就看看吧。简单地浏览一下,终于知道如果文件里有非ASCII字符,需要在第一行或第二行指定编码声明。把ChineseTest.py文件的编码重新改为ANSI,并加上编码声明:
# coding=gbk
s = "中文"
print s
再试一下:
E:\Project\Python\Test>python ChineseTest.py
中文
正常咯:)
(二)
看一看它的长度:
# coding=gbk
s = "中文"
print len(s)
结果:4。
s这里是str类型,所以计算的时候一个中文相当于两个英文字符,因此长度为4。
我们这样写:
# coding=gbk
s = "中文"
s1 = u"中文"
s2 = unicode(s, "gbk") #省略参数将用python默认的ASCII来解码
s3 = s.decode("gbk") #把str转换成unicode是decode,unicode函数作用与之相同
print len(s1)
print len(s2)
print len(s3)
结果:
2
2
2
(三)
接着来看看文件的处理:
建立一个文件test.txt,文件格式用ANSI,内容为:
abc中文
用python来读取
# coding=gbk
print open("Test.txt").read()
结果:abc中文
把文件格式改成UTF-8:
结果:abc涓?枃
显然,这里需要解码:
# coding=gbk
import codecs
print open("Test.txt").read().decode("utf-8")
结果:abc中文
上面的test.txt我是用Editplus来编辑的,但当我用Windows自带的记事本编辑并存成UTF-8格式时,
运行时报错:
Traceback (most recent call last):
  File "ChineseTest.py", line 3, in
    print open("Test.txt").read().decode("utf-8")
UnicodeEncodeError: 'gbk' codec can't encode character u'\ufeff' in position 0: illegal multibyte sequence
原来,某些软件,如notepad,在保存一个以UTF-8编码的文件时,会在文件开始的地方插入三个不可见的字符(0xEF 0xBB 0xBF,即BOM)。
因此我们在读取时需要自己去掉这些字符,python中的codecs module定义了这个常量:
# coding=gbk
import codecs
data = open("Test.txt").read()
if data[:3] == codecs.BOM_UTF8:
data = data[3:]
print data.decode("utf-8")
结果:abc中文
(四)一点遗留问题
在第二部分中,我们用unicode函数和decode方法把str转换成unicode。为什么这两个函数的参数用"gbk"呢?
第一反应是我们的编码声明里用了gbk(# coding=gbk),但真是这样?
修改一下源文件:
# coding=utf-8
s = "中文"
print unicode(s, "utf-8")
运行,报错:
Traceback (most recent call last):
  File "ChineseTest.py", line 3, in
    s = unicode(s, "utf-8")
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid data
显然,如果前面正常是因为两边都使用了gbk,那么这里我保持了两边utf-8一致,也应该正常,不至于报错。
更进一步的例子,如果我们这里转换仍然用gbk:
# coding=utf-8
s = "中文"
print unicode(s, "gbk")
结果:中文
翻阅了一篇英文资料,它大致讲解了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。
最后测试:
# coding=utf-8
s = "中文"
print unicode(s, "cp936")
结果:中文

转载:Python 编码问题整理
几个概念性的东西
ANSCII:
标准的 ANSCII 编码只使用7个比特来表示一个字符,因此最多编码128个字符。扩充的 ANSCII 使用8个比特来表示一个字符,最多也只能
编码 256 个字符。
UNICODE:
使用2个甚至4个字节来编码一个字符,因此可以将世界上所有的字符进行统一编码。
UTF:
UNICODE编码转换格式,就是用来指导如何将 unicode 编码成适合文件存储和网络传输的字节序列的形式 (unicode ->
str)。像其他的一些编码方式 gb2312, gb18030, big5 和 UTF 的作用是一样的,只是编码方式不同。
Python 里面有两种数据模型来支持字符串这种数据类型,一种是 str,另外一种是 unicode ,它们都是 sequence 的派生类
型,这个可以参考 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,相反的,解码就
是 str -> unicode。
下面剩下的问题就是确定何时需要进行编码或者解码了,像一些库是 unicode 版的,这样我们在将这些库函数的返回值进行传输或者写入文件的时候就
要考虑将它编码成合适的类型。
关于文件开头的"编码指示",也就是 # -*- coding: -*- 这个语句。Python 默认脚本文件都是 ANSCII 编码的,当文件
中有非 ANSCII 编码范围内的字符的时候就要使用"编码指示"来修正。
关于 sys.defaultencoding,这个在解码没有明确指明解码方式的时候使用。比如我有如下代码:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
s = '中文'  # 注意这里的 str 是 str 类型的,而不是 unicode
s.encode('gb18030')
这句代码将 s 重新编码为 gb18030 的格式,即进行 unicode -> str 的转换。因为 s 本身就是 str 类型的,因此
Python 会自动的先将 s 解码为 unicode ,然后再编码成 gb18030。因为解码是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('gb18030')
二是更改 sys.defaultencoding 为文件的编码方式
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
reload(sys) # Python2.5 初始化后会删除 sys.setdefaultencoding 这个方法,我们需要重新载入
sys.setdefaultencoding('utf-8')
str = '中文'
str.encode('gb18030')

  
转载:
Python操作MySQL以及中文乱码的问题
Python操作MySQL需要安装Python-MySQL
可以从网上搜索一下,和一般的Python包一样安装
安装好之后,模块名字叫做MySQLdb ,在Window和Linux环境下都可以使用,试验了一下挺好用,
不过又发现了烦人的乱麻问题,最后用了几个办法,解决了!
我用了下面几个措施,保证MySQL的输出没有乱麻:
    1 Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8)    2 MySQL数据库charset=utf-8     3 Python连接MySQL是加上参数 charset=utf8     4 设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)
mysql_test.py
   

#encoding=utf-8

import sys

import MySQLdb


reload(sys)

sys.setdefaultencoding('utf-8')


db=MySQLdb.connect(user='root',charset='utf8')

cur=db.cursor()

cur.execute('use mydb')

cur.execute('select * from mytb limit 100')


f=file("/home/user/work/tem.txt",'w')


for i in cur.fetchall():

    f.write(str(i))

    f.write(" ")


f.close()

cur.close()
上面是linux上的脚本,windows下运行正常!
注:MySQL的配置文件设置也必须配置成utf8
设置 MySQL 的 my.cnf 文件,在 [client]/[mysqld]部分都设置默认的字符集(通常在/etc/mysql/my.cnf):
[client]
default-character-set = utf8
[mysqld]
default-character-set = utf8
转载:实现URL编码解码的python程序
import urllib
import sys
string = sys.argv[1]
string = unicode(string,"gbk")
utf8_string = string.encode("utf-8")
gbk_string=string.encode("gbk")
gbk=urllib.quote(gbk_string)
utf8=urllib.quote(utf8_string)
print gbk
print utf8
解码使用unqute和decode函数


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/68206/showart_668359.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP