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)
    
    
  • 相关阅读:
    单调队列
    2019牛客暑期多校训练营(第一场)
    没有上司的舞会
    飞碟解除器
    最小费用最大流
    prim
    merge_sort
    CCF认证之——相反数
    CCF考试认证模拟练习——数字排序
    算法之分治法
  • 原文地址:https://www.cnblogs.com/wzbk/p/14685721.html
Copyright © 2011-2022 走看看