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的字符串
执行结果为:
��,其实上面的过程略显复杂,有更简单的:
print test.decode(“unicode-escape”)
print eval(“u’%s’” % test)
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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- Linux 与 Windows 对UNICODE 的处理方式
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例