import shutil
import sys
import os
import stat
""" Usage:
convert.py Filelist <1628|8216>
"""
for argv in sys.argv[1:-1] :
f_in = open(argv, 'rb')
f_out = open(argv +'.tmp', 'wb')
if sys.argv[-1] == '1628' :
result_f = codecs.EncodedFile(f_in, 'utf8', 'utf16')
else :
result_f = codecs.EncodedFile(f_in, 'utf16', 'utf8')
for chars in result_f.read() :
f_out.write(chars)
f_in.close()
f_out.close()
os.chmod(argv, stat.S_IWRITE)
os.remove(argv)
shutil.move(argv + '.tmp', argv)
不好意思:-P
说实话,直到现在,还时不时的在使用 Python 的过程中遇到编码出错的问题。在这里讨论一下,以后整理一下留作参考。
先说说我目前对 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') -- Jerry Lee University of Jinan
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''
暂无留言
文章出处:DIY部落(http://www.diybl.com/course/1_web/webjs/2008224/101726.html) 因为平时文件编码总是不确定,到最后做完了上面又说转成xxx编码.转来转去的,烦了,干脆自己写个自动转换的程序,想必大家也有此痛苦的经历吧 不 过不只是这个用途的,以前我用palm系统的treo650看电子书的时候,有些html文档下载下来都是utf-8的,palm系统是不支持这个的,要 转换为gb,当然主要是些英文技术文档...以前用软件转过,虽说也是批量,但为了这点小事装个那么大的软件,感觉系统又乱七八糟的..不爽...呵呵 现在只是放出python写的脚本源代码,等有空的时候方便大家将脚本嵌入c++编译成exe档的.当然用py2exe可以直接转换,但是那样修改转换编码就不是很方便了,或者我必须再搞一个ini的配置文件...嵌入c++的好处是大家可以直接修改脚本.呵呵 放在你要批量转换的文件和文件夹的根目录下就可以了 下面是code: """ #set your file dir #specify file list #encode & decode setting def main(dir_list): get_dir_son_list(dir_list) encode_file(_specify_file_list) #get the dir list def encode_file(specify_file_list): try: try: except IOError: except Exception, e: main(FILE_ENCODE_DIR_LIST) |