代码之家  ›  专栏  ›  技术社区  ›  hamdiakoguz Sukima

如何在python中取消引用url编码的unicode字符串?

  •  54
  • hamdiakoguz Sukima  · 技术社区  · 18 年前

    我有一个unicode字符串,比如“Tan±m”,不知怎么编码为“Tan%u0131m”。如何将此编码字符串转换回原始unicode。 显然urllib.unquote不支持unicode。

    5 回复  |  直到 9 年前
        1
  •  70
  •   Aaron Maenpaa    18 年前

    %uXXXX是一个 non-standard encoding scheme 尽管JavaScript领域仍存在实现,但w3c拒绝了这一点。

    更常见的技术似乎是对字符串进行UTF-8编码,然后使用%XX对生成的字节进行%转义。该方案由urllib.unquote支持:

    >>> urllib2.unquote("%0a")
    '\n'
    

    不幸的是,如果你真的 需要 要支持%uXXXX,您可能需要滚动自己的解码器。否则,更可取的做法可能是简单地对unicode进行UTF-8编码,然后对生成的字节进行%转义。

    一个更完整的例子:

    >>> u"Tanım"
    u'Tan\u0131m'
    >>> url = urllib.quote(u"Tanım".encode('utf8'))
    >>> urllib.unquote(url).decode('utf8')
    u'Tan\u0131m'
    
        2
  •  11
  •   Markus Jarderot    18 年前
    def unquote(text):
        def unicode_unquoter(match):
            return unichr(int(match.group(1),16))
        return re.sub(r'%u([0-9a-fA-F]{4})',unicode_unquoter,text)
    
        3
  •  7
  •   Ali Afshar    18 年前

    如果你一定要这样做(我真的同意“非标准”的说法):

    from urllib import unquote
    
    def unquote_u(source):
        result = unquote(source)
        if '%u' in result:
            result = result.replace('%u','\\u').decode('unicode_escape')
        return result
    
    print unquote_u('Tan%u0131m')
    
    > Tanım
    
        4
  •  4
  •   Jermaine Jermaine    17 年前

    上述版本中存在一个错误,当字符串中既有ascii编码的字符又有unicode编码的字符时,有时会出现问题。我认为这特别是当除了unicode之外还有128位以上的字符,如'\xab'时。

    例如,“%5B%AB%u03E1%BB%5D”导致此错误。

    我发现如果你先做unicode,问题就消失了:

    def unquote_u(source):
      result = source
      if '%u' in result:
        result = result.replace('%u','\\u').decode('unicode_escape')
      result = unquote(result)
      return result
    
        5
  •  1
  •   Martijn Pieters    7 年前

    您有一个使用 non-standard encoding scheme ,被标准机构拒绝,但仍由一些编码器生产。蟒蛇 urllib.parse.unquote() 函数无法处理这些。

    幸运的是,创建自己的解码器并不难。 %uhhhh 条目旨在 UTF-16 这里有代码点,所以我们需要采取 surrogate pairs 考虑到。我也见过 %hh 代码点混杂在一起,增加了混乱。

    考虑到这一点,这里有一个在Python 2和Python 3中都能工作的解码器,只要你传入一个 str Python 3中的对象(Python 2不太关心):

    try:
        # Python 3
        from urllib.parse import unquote
        unichr = chr
    except ImportError:
        # Python 2
        from urllib import unquote
    
    def unquote_unicode(string, _cache={}):
        string = unquote(string)  # handle two-digit %hh components first
        parts = string.split(u'%u')
        if len(parts) == 1:
            return parts
        r = [parts[0]]
        append = r.append
        for part in parts[1:]:
            try:
                digits = part[:4].lower()
                if len(digits) < 4:
                    raise ValueError
                ch = _cache.get(digits)
                if ch is None:
                    ch = _cache[digits] = unichr(int(digits, 16))
                if (
                    not r[-1] and
                    u'\uDC00' <= ch <= u'\uDFFF' and
                    u'\uD800' <= r[-2] <= u'\uDBFF'
                ):
                    # UTF-16 surrogate pair, replace with single non-BMP codepoint
                    r[-2] = (r[-2] + ch).encode(
                        'utf-16', 'surrogatepass').decode('utf-16')
                else:
                    append(ch)
                append(part[4:])
            except ValueError:
                append(u'%u')
                append(part)
        return u''.join(r)
    

    该功能深受 current standard-library implementation .

    演示:

    >>> print(unquote_unicode('Tan%u0131m'))
    Tanım
    >>> print(unquote_unicode('%u05D0%u05D9%u05DA%20%u05DE%u05DE%u05D9%u05E8%u05D9%u05DD%20%u05D0%u05EA%20%u05D4%u05D8%u05E7%u05E1%u05D8%20%u05D4%u05D6%u05D4'))
    איך ממירים את הטקסט הזה
    >>> print(unquote_unicode('%ud83c%udfd6'))  # surrogate pair
    🏖
    >>> print(unquote_unicode('%ufoobar%u666'))  # incomplete
    %ufoobar%u666
    

    该函数适用于Python 2(在2.4-2.7上测试)和Python 3(在3.3-3.8上测试)。