Python 爬蟲遇到形如 小說 的編碼如何轉換為中文?


<dt>學科主題:</dt> <dd><a href="openlink.php?keyword=%E9%95%BF%E7%AF%87%E5%B0%8F%E8%AF%B4">&#x957f;&#x7bc7;&#x5c0f;&#x8bf4;</a>-&#x4e2d;&#x56fd;-&#x5f53;&#x4ee3;</dd> </dl> <dl class="booklist"> <dt>中圖法分類號:</dt> <dd><a href="openlink.php?coden=I247.5">&#x0049;&#x0032;&#x0034;&#x0037;&#x002e;&#x0035;</a></dd> </dl> <dl class="booklist"> <dt>提要文摘附注:</dt> <dd>&#x5c0f;&#x8bf4;&#x4e2d;&#x7684;&#x4e3b;&#x4eba;&#x516c;&#xff0c;&#x6b63;&#x662f;&#x56e0;&#x4e3a;&#x5f53;&#x5e74;&#x76d7;&#x5893;&#x7684;&#x7237;&#x7237;&#x4eba;&#x8d58;&#x676d;&#x5dde;&#x800c;&#x8eab;&#x5728;&#x676d;&#x5dde;&#xff0c;&#x5f00;&#x4e86;&#x4e00;&#x5bb6;&#x5c0f;&#x7684;&#x53e4;&#x8463;&#x94fa;&#x5b50;&#xff0c;&#x5b88;&#x62a4;&#x7740;&#x90a3;&#x7fa4;&#x957f;&#x6c99;&#x571f;&#x592b;&#x5b50;&#x4ece;&#x53e4;&#x5893;&#x4e0d;&#x77e5;&#x540d;&#x602a;&#x7269;&#x636d;&#x4e2d;&#x62fc;&#x547d;&#x62a2;&#x51fa;&#x7684;&#x6218;&#x56fd;&#x5e1b;&#x4e66;&#x2026;&#x2026;</dd> </dl>


# tested under python3.4 def convert(s): s = s.strip('&#x;') # 把'&#x957f;'變成'957f' s = bytes(r'\u' + s, 'ascii') # 把'957f'轉換成b'\\u957f' return s.decode('unicode_escape') # 調用bytes對象的decode,encoding用unicode_escape,把b'\\u957f'從unicode轉義編碼解碼成unicode的'長'。具體參見codecs的文檔 print(convert('&#x957f;')) # => '長'


全篇替換

import re print(re.sub(r'&#x....;', lambda match: convert(match.group()), ss))

全文替換后的結果:

<dt>學科主題:</dt> <dd><a href="openlink.php?keyword=%E9%95%BF%E7%AF%87%E5%B0%8F%E8%AF%B4">長篇小說</a>-中國-當代</dd> </dl> <dl class="booklist"> <dt>中圖法分類號:</dt> <dd><a href="openlink.php?coden=I247.5">I247.5</a></dd> </dl> <dl class="booklist"> <dt>提要文摘附注:</dt> <dd>小說中的主人公,正是因為當年盜墓的爺爺人贅杭州而身在杭州,開了一家小的古董鋪子,守護着那群長沙土夫子從古墓不知名怪物捭中拼命搶出的戰國帛書……</dd>


# for python2.7 def convert(s): return ''.join([r'\u', s.strip('&#x;')]).decode('unicode_escape') ss = unicode(ss, 'gbk') # convert gbk-encoded byte-string ss to unicode string import re print re.sub(r'&#x....;', lambda match: convert(match.group()), ss)


這個是 charref, HTML 的解析庫都可以處理好, 不需要手工處理.
Python 標准庫有 HTMLParser (html.parser in Python 3)
第三方庫推薦 BeautifulSoup


免責聲明!

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



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