您的位置:首页 > 编程语言 > Python开发

Python解析文件中的unicode字符

2016-06-15 22:40 501 查看
假设一个文件里的字符内容为:

test = ‘\u5927\u5bb6\u597d\u6211\u662f\u4e00\u4e2a\u5fae\u5e97\u7ecf\u8425\u8005\uff0c\u4e3b\u8981\u7ecf\u8425\u4ea7\u54c1\u6709\uff0c\u7ae5\u978b\uff0c\u513f

\u7ae5\u670d\uff0c\u513f\u7ae5\u56fe\u4e66\u8bf7\u5927\u5bb6\u5feb\u6765\u770b\u4e00\u770b’

用变量test表示

每个\uxxxx都是长度都是1,每一位是16进制的,转换成十进制数字,然后可以转换为unicode的长度为3的字符串

#!/usr/bin/env python
import sys
#-*- coding:utf8 -*-

test = '\u5927\u5bb6\u597d\u6211\u662f\u4e00\u4e2a\u5fae\u5e97\u7ecf\u8425\u8005\uff0c\u4e3b\u8981\u7ecf\u8425\u4ea7\u54c1\u6709\uff0c\u7ae5\u978b\uff0c\u513f\u7ae5\u670d\uff0c\u513f\u7ae5\u56fe\u4e66\u8bf7\u5927\u5bb6\u5feb\u6765\u770b\u4e00\u770b'

ch2num = {
'0':0,
'1':1,
'2':2,
'3':3,
'4':4,
'5':5,
'6':6,
'7':7,
'8':8,
'9':9,
'a':10,
'b':11,
'c':12,
'd':13,
'e':14,
'f':15
}

for line in open("input.dat"):
for item in line.strip().split("\u"):
if item == "" : continue
bit_num = [[len(item)-index-1, ch2num[item[index]]] for index, s in enumerate(item)]
total = 0
for tp in bit_num:
bit, num = tp
total += num * 16 ** bit
sys.stdout.write(unichr(total))
print ""


执行结果为:

lming_08@localhost:~/workspace_python/unicode_parse$ ./unicode.py
大家好我是一个微店经营者,主要经营产品有,童鞋,儿童服,儿童图书请大家快来看一看


��,其实上面的过程略显复杂,有更简单的:

print test.decode(“unicode-escape”)

print eval(“u’%s’” % test)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python unicode