<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> </dl>
# tested under python3.4 def convert(s): s = s.strip('&#x;') # 把'长'變成'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('长')) # => '長'
全篇替換
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