Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 解码URL中的转义字符_Python_Escaping - Fatal编程技术网

Python 解码URL中的转义字符

Python 解码URL中的转义字符,python,escaping,Python,Escaping,我有一个包含带有转义字符的URL的列表。这些字符是由urllib2.urlopen在恢复html页面时设置的: http://www.sample1webpage.com/index.php?title=%E9%A6%96%E9%A1%B5&action=edit http://www.sample1webpage.com/index.php?title=%E9%A6%96%E9%A1%B5&action=history http://www.sample1webpage.com

我有一个包含带有转义字符的URL的列表。这些字符是由
urllib2.urlopen
在恢复html页面时设置的:

http://www.sample1webpage.com/index.php?title=%E9%A6%96%E9%A1%B5&action=edit
http://www.sample1webpage.com/index.php?title=%E9%A6%96%E9%A1%B5&action=history
http://www.sample1webpage.com/index.php?title=%E9%A6%96%E9%A1%B5&variant=zh 
有没有一种方法可以将它们转换回python中的未转换形式

注意:URL以utf-8编码

urllib.unquote(
string

%xx
转义替换为它们的等效单字符

例如:
unquote('/%7econolly/')
产生
'/~connolly/'

然后解码


更新: 对于Python 3,编写以下代码:

import urllib.parse
urllib.parse.unquote(url)

您可以使用

urlib.unquote\u plus

>>> import urllib
>>> urllib.unquote('erythrocyte+membrane+protein+1%2C+PfEMP1+%28VAR%29')
'erythrocyte+membrane+protein+1,+PfEMP1+(VAR)'
>>> urllib.unquote_plus('erythrocyte+membrane+protein+1%2C+PfEMP1+%28VAR%29')
'erythrocyte membrane protein 1, PfEMP1 (VAR)'

如果您使用的是
Python3
,您可以使用:

import urllib.parse
urllib.parse.unquote(url)

当我使用unquote(顺便说一句,谢谢…)时,它会显示这个字符串\xe9\xa6\x96\xe9\xa1\xb5&action=edi,我知道它们是中文字符。。。我怎么能看到他们?我猜这是unicode,对吧?这已经在你的问题中了。这些是UTF-8字节;您可以使用
b“\xe9\xa6\x96\xe9\xa1\xb5”将它们转换为Unicode字符串。解码(“utf-8”)
(现在使用更现代的Python语法)。如我前面所说,unquote显示sample.com/index.php?title=\xe9\xa6\x96\xe9\xa1\xb5&action=edi。。。也许我没有很好地解释自己在这种情况下。。。但是这个url是中文的,我想解码成它的原始字符,而不是unquoteone@dyoser你需要把这个放在你的问题里。@root45这是对一个答案的评论。。。所以这里很好。感谢您的欣赏。请注意,对于python3,这是
urllib.parse.unquote
对于python3,它也在
urllib.request.unquote
中,当有一个内置库可以满足您的需要时,您为什么要手动使用regex和lambdas?这可能是一个更周到的解决方案
urlib2
不是标准python发行版的一部分
re
is.也在
urlib.request.unquote
import urllib.parse
urllib.parse.unquote(url)