程序员

python2.7 处理中文

2018-09-04  本文已影响0人  飞飞羊

python2的中文处理很麻烦,特做总结。


unicode 与 utf-8

默认的中文使用的是utf-8编码,前面加u的是Unicode编码:


写文件的字符串不能用Unicode编码,可以用utf-8编码,同理,其它的IO也应该使用utf-8:
# utf-8编码下可以正常写文件
s = '等等'
with open('testData.txt', 'w') as fOut:
    fOut.write(s)
 
# unicode编码时写文件会抛出编码异常
s = u'等等'
with open('testData.txt', 'w') as fOut:
    fOut.write(s)

unicode编码是python的工作编码,utf-8编码是python的IO编码。
即字符串在内存中编辑时应该使用Unicode编码,字符串写入文件前应该转换成utf-8编码。文件中读取出的字符串是utf-8编码,对这字符串进行编辑前应该转换成Unicode编码。
为什么编辑时要用Unicode编码而不直接用utf-8编码?且看下图:


如上,utf-8编码时字符串中的每个元素是字节,unicode 编码时字符串中的元素才是一个汉字。(这也是为什么要用utf-8写文件而不用unicode)

encode 与 decode

unicode和utf-8的转换需要使用encode和decode,这里主动忽略gb编码。
encode是将当前的字符串(字节串)编码成目标编码的字节串,decode是将当前的字节串解码为Unicode编码的字符串。所以才说Unicode是工作编码嘛。
使用示例:

s = u'打的'    # unicode字符串
s1 = s.encode('utf-8')     # 将Unicode字符串编码成utf-8字节串
s2 = s1.decode('utf-8')    # 将utf-8字节串解码成unicode字符串
s = '打的'     # utf-8字节串
s2 = s.decode('utf-8')            # 将utf-8字节串解码成Unicode字符串
s1 = s.encode('unicode escape')   # 将utf-8字节串编码成Unicode字节串
s2 = s1.decode('utf-8')           # 将Unicode字节串解码成Unicode字符串

用法分析:


如上图,可以看到,即使两个字符串的编码不同,还是会判定他们相等的。

读写文件

一般来说,读文件出来的字符串是utf-8字符,想要对此进行处理,建议先将其decode成Unicode字符串。
写文件时要十分注意这个字符串是不是utf-8。不是就得先encode。
如果嫌麻烦,也可以直接在开头加这几句:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

JSON 的 load 与 dump

用load函数加载json文件时,中文字符会被转换成\u开头的unicode码。

用dump函数写json文件时,需要注意一个参数 ensure_ascii,此参数指定是否保证文件只含ASCII字符串,默认为True。所以要将其指定为False不然中文就被转码了:

with open("./test.json", "w") as f:
    json.dump(elements, f, ensure_ascii=False)

也可以不直接dump而是先dumps再write:

dataOut = json.dumps(dataOut)
with open('robot_info_2.json', 'w') as fOut:
    fOut.write(dataOut.decode('unicode escape').encode('utf-8'))

案例1:将\u字符串转换成中文

s = '\u6253\u7684'
s1 = s.decode('unicode escape') 
上一篇 下一篇

猜你喜欢

热点阅读