代码之家  ›  专栏  ›  技术社区  ›  Elliott Weaver

如何用正确的Unicode字符替换转义的Unicode字符?

  •  0
  • Elliott Weaver  · 技术社区  · 6 年前

    我有一根这样的绳子:

    'https://www.jobtestprep.co.uk/media/24543/xnumber-series-big-1.png,qanchor\\u003dcenter,amode\\u003dcrop,awidth\\u003d473,aheight\\u003d352,arnd\\u003d131255524960000000.pagespeed.ic.YolXsWmhs0.png'
    

    我需要替换任意转义的Unicode字符( '\\uXXXX' )用它的等价物 未捕获 Unicode字符( '\uXXXX' )我已经让Regex提取所有必要的部分 '\\uxxxx' 部分和 'XXXX' 零件 re.sub() )但是我找不到一种方法来替换正确的部分 \u{} 因为python给出了一个unicode错误并需要一个预先填充的字符,例如 '\u003d' . 使用原始字符串不起作用 '\u{}' 刚转换回 '\\u{}' 最后我们回到了开始的地方。

    有办法吗?如果您想要一个代码示例,可以在这里查看它:

    # data loaded from a https://www.google.com/search image search
    
    results_source = urllib.request.urlopen(url_request).read().decode()
    searched_results = re.findall(r"(?<=,\"ou\":\")[^\s]+[\w](?=\",\"ow\")", results_source)
    
    for count, unicode in enumerate(re.findall(r"(?<=\\u)....", searched_results[i])):
        searched_results[i] = re.sub(re.findall(r"\\u....", searched_results[i])[count], r"\u{}".format(unicode), searched_results[i])
    

    searched_results 是返回的结果列表。列表中项目的一个例子是上面给出的字符串。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Martijn Pieters    6 年前

    searched_results = re.findall(r"(?<=,\"ou\":\")[^\s]+[\w](?=\",\"ow\")", results_source)
    

    " \uxxxx

    searched_results = map(json.loads, re.findall(r"(?<=,\"ou\":)\"[^\s]+[\w]\"(?=,\"ow\")", results_source))
    

    BeautifulSoup

    import json
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(results_source, 'html.parser')
    search_results = [json.loads(t.text)['ou'] for t in soup.select('.rg_meta')]
    

    <div class="rg_meta" ...> ou

        2
  •  0
  •   Vladimir Vernidubov    6 年前

    >>> url = (
    ...    'https://www.jobtestprep.co.uk/media/24543/xnumber-series-'
    ...    'big-1.png,qanchor\\u003dcenter,amode\\u003dcrop,awidth\\u003d473,'
    ...    'aheight\\u003d352,arnd\\u003d131255524960000000.pagespeed.ic.YolXsWmhs0.png'
    ... )
    >>> url = url.encode('utf-8').decode('unicode_escape')
    >>> print(url)
    https://www.jobtestprep.co.uk/media/24543/xnumber-series-big-1.png,qanchor=center,amode
    =crop,awidth=473,aheight=352,arnd=131255524960000000.pagespeed.ic.YolXsWmhs0.png
    >>>