【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');

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM