zoukankan      html  css  js  c++  java
  • Python 爬虫遇到形如 小说 的编码如何转换为中文?

    遇到问题

    a target="_blank" title="音乐接力/全能投屏/触碰联网/米家智能场景">
    

    解决办法 python3 中

    
    # 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('长')) # => '长'
    

    我的执行效果

    title = "音乐接力/全能投屏/触碰联网/米家智能场景"
    
    title = title.replace("&#x", "").replace(";", ",")
    
    tirle = title.replace('/', '').split(',')
    
    for i in title:
    
        if len(i) == 4:
            s = bytes(r'u' + i, 'ascii')
            print(s.decode(
                'unicode_escape'))
    
    音乐接力全能投屏触碰联网米家智能场景
    

    python 2 中

    # 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)
    
    
  • 相关阅读:
    OneSQL安装
    Dropbox可伸缩性设计最佳实践分享
    软件开发实践的24条军规
    最精彩的英语学习经验总结:俺的英语之路
    Facebook和Google如何激发工程师的创造力
    十种更好的表达“你的代码写的很烂”的方法
    一次java程序的重构
    漂亮代码
    一段代码引发的思考
    最难忘的Bug调试经历
  • 原文地址:https://www.cnblogs.com/wzbk/p/14685721.html
Copyright © 2011-2022 走看看