Python中还原JavaScript的escape函数编码后字符串的方法

WBOY
Release: 2016-06-16 08:42:36
Original
1549 people have browsed it

遇到一个问题需要用Python把JavaScript中escape的中文给还原,但找了大半天,也没有找到答案,只好自己深入研究解决方案。
我们先来看在js中escape一段文字的编码

复制代码 代码如下:

a = escape('这是一串文字');
alert(a);

输出:
复制代码 代码如下:

%u8FD9%u662F%u4E00%u4E32%u6587%u5B57

咋一看,就感觉有点类似json格式,我们来看看标准的json格式编码同样的汉子“这是一串文字”
复制代码 代码如下:

# encoding=utf-8
import json
a = '这是一串文字'
print json.dumps(a)

输出:
复制代码 代码如下:
"\u8fd9\u662f\u4e00\u4e32\u6587\u5b57"
经过对比,其实就是js escape编码每个汉子都是“%u”符号加4位字符编码,而json编码每个汉子都是“\u”符号加4位字符编码,这样的话,我们可以利用字符串替换操作还原json格式,然后再使用json模块loads就好
复制代码 代码如下:

# encoding=utf-8
import json
 
# js escape 字符串编码
c = '%u8FD9%u662F%u4E00%u4E32%u6587%u5B57'
 
# 还原Json对象
jsonObj =  '"'+"".join([(i and "\\"+i) for i in c.split('%')])+'"'
 
print json.loads(jsonObj)

特别记得在把“%”替换为“\”符号以后还要再使用双引号把字符串包一下,才能算是一个json对象,然后才能json.loads出来
后来,好不容易在一个站点上看到了更简便的方法。代码如下:
复制代码 代码如下:

# encoding=utf-8
c = '%u8FD9%u662F%u4E00%u4E32%u6587%u5B57'
print "".join([(len(i)>0 and unichr(int(i,16)) or "") for i in c.split('%u')])

它的思路其实都差不多,把“%u”号替换掉,剩下每一个都是4位固定长度的字符编码,最后在unichr反编码回中文字符。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!