python 学习~unicode 编码

如果代码文件需要制定编码格式如utf-8:

1.要在文件开始时写如下注释

# coding=utf-8 

2.或则 使用以下代码

import sys

reload sys

sys.setdefaultencoding('utf-8')


说明:unicode支持不同的编码方式,最著名的的是utf-8.  ASCII字符 的utf-8 编码 与ASCII编码完全一致。

            此外,在程序中不要使用string模块,使用unicode()和unichar()函数代替str()和chr() 函数  

一般对文件操作、socket操作,需要把内容转换为utf-8,处理完后再转换回来。

如 以utf-8编码格式 写入文件,  读文件后 可进行解码


 

# coding=utf-8
def  toUTF_8(s):
    if type(s).__name__=='unicode':
        return s.encode('utf-8')
    else:
        return s
    
def toUnicode(s):
    if type(s).__name__!='unicode':
        return s.decode('utf-8')
    else:
        return s    

CODEC = 'utf-8'
FILE = 'unicode.txt'
hello_out = u"世界\n"

bytes_out = toUTF_8(hello_out) 
f = open(FILE, "w")
f.write(bytes_out)
f.close()


f = open(FILE, "r")
bytes_in = f.read()
f.close()
hello_in = toUnicode(bytes_in)
print hello_in


 


 

posted @ 2013-05-07 19:27  javawebsoa  Views(225)  Comments(0)    收藏  举报