python爬虫 - Python 爬虫遇到形如 小说 的编码如何转换为中文?
迷茫
迷茫 2017-04-17 13:24:20
[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>

如何解决?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(2)
PHP中文网

# 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>
        </dl>
# 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)
PHP中文网

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号