【python】or【php】网页中字符编码转换,将反斜杠u u字符串转为unicode/utf8

有的时候我们用python来抓取网页会得到类似 '\u003C\u0066\u0072\u006F\u006D\u003E' 或者 '%u003c%u0062%u0072%u003e%u003c%u0064%u0069%u0076%u0020%u0063%u006c......' 那么应该怎么处理呢?

python

这种情况就是把 unicode直接输出到文本中了,现在需要把它还原回去。

解决:

In [23]: s1
Out[23]: '\u003C\u0066\u0072\u006F\u006D\u003E'

In [24]: s2
Out[24]: '%u003c%u0062%u0072%u003e%u003c%u0064%u0069%u0076%u0020%u0063%u006c......'

In [25]: print s1.decode('unicode-escape')
<from>

In [26]: print s2.replace("%", "\").decode('unicode-escape')
<br><div cl......

另一种方式是使用json

def to_chinese(unicode_str):
    x = json.loads('{"chinese":"%s"}' % unicode_str)
    return x['chinese']

php

$str = preg_replace("/\\u([0-9a-f]{3,4})/i", "&#x\1;", $str);
$str = html_entity_decode($str, null, 'UTF-8');
原文地址:https://www.cnblogs.com/forforever/p/12713907.html