Python获取到小&#x8bf4这样编码怎么转义,,
学科主题:
<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>

如何解决?

这个是 charref, HTML 的解析库都可以处理好, 不需要手工处理.
Python 标准库有 HTMLParser (html.parser in Python 3)
第三方库推荐 BeautifulSoup


# tested under python3.4def 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 reprint(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>        </dl>
# for python2.7def convert(s):    return ''.join([r'\u', s.strip('&#x;')]).decode('unicode_escape')ss = unicode(ss, 'gbk') # convert gbk-encoded byte-string ss to unicode stringimport reprint re.sub(r'&#x....;', lambda match: convert(match.group()), ss)

编橙之家文章,

评论关闭