用Python将文本解码为ASCII
如何解码这样的unicode字符串:
what%2527s%2bthe%2btime%252c%2bnow%253f
变成这样的ascii字符串:
what's+the+time+now
3 个回答
0
你可以用类似下面的方式把%(hex)格式的字符转换过来:
import re
def my_decode(s):
re.sub('%([0-9a-fA-F]{2,4})', lambda x: unichr(int(x.group(1), 16)), s)
s = u'what%2527s%2bthe%2btime%252c%2bnow%253f'
print my_decode(s)
这样就能得到一个unicode字符串
u'what\u2527s+the+time\u252c+now\u253f'
不过我不太确定你怎么知道要把\u2527转换成单引号,或者在转换成ascii时要去掉\u253f和\u252c这些字符。
0
像这样吗?
title = u"what%2527s%2bthe%2btime%252c%2bnow%253f"
print title.encode('ascii','ignore')
另外,可以看看 这个链接
6
在你的情况下,这个字符串被解码了两次,所以我们需要解码两次才能把它恢复回来。
In [1]: import urllib
In [2]: urllib.unquote(urllib.unquote("what%2527s%2bthe%2btime%252c%2bnow%253f") )
Out[3]: "what's+the+time,+now?"