【问题标题】:Python decode text to asciiPython将文本解码为ascii
【发布时间】:2011-09-23 14:26:56
【问题描述】:

如何像这样解码 unicode 字符串:

what%2527s%2bthe%2btime%252c%2bnow%253f

像这样进入ascii:

现在是什么+时间+现在

【问题讨论】:

标签: python unicode decode


【解决方案1】:

在您的情况下,字符串被解码了两次,因此我们需要取消引用两次才能将其取回

In [1]: import urllib
In [2]: urllib.unquote(urllib.unquote("what%2527s%2bthe%2btime%252c%2bnow%253f") )
Out[3]: "what's+the+time,+now?"

【讨论】:

  • 至少外部的unquote 可能想改成unquote_plus;我猜那些 +s 最初是空格,作为 HTML 表单提交(它对 + 的处理与常规 URL 编码略有不同)。但是,是的,双重编码的字符串是一个危险信号,表示“有人在这里做错了……”
【解决方案2】:

这样的?

title = u"what%2527s%2bthe%2btime%252c%2bnow%253f"
print title.encode('ascii','ignore')

另外,看看this

【讨论】:

    【解决方案3】:

    您可以使用以下方式转换 %(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 字符

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      相关资源
      最近更新 更多