Python解析文件中的unicode字符

假设一个文件里的字符内容为:
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 
大家好我是一个微店经营者,主要经营产品有,童鞋,儿童服,儿童图书请大家快来看一看

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

  1. print test.decode(“unicode-escape”)
  2. print eval(“u’%s’” % test)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值