V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
lixia625
V2EX  ›  Python

[求问]有没有办法将一个包含不同编码的 list 转换为一个相同编码的 string

  •  
  •   lixia625 · 2015-07-15 19:43:33 +08:00 · 2603 次点击
    这是一个创建于 3221 天前的主题,其中的信息可能已经有所发展或是发生改变。


    元素可能是utf8或ascii,也可能已经是同一种编码
    也就是说谁是哪一种编码是不确定的

    a=[u'\u54c8\u54c8', '\xba\xc7\xba\xc7']
    u'\u54c8\u54c8\u5475\u5475'

    6 条回复    2015-07-16 09:00:55 +08:00
    ayang23
        1
    ayang23  
       2015-07-15 19:55:57 +08:00   ❤️ 2
    你的字符串里现在有两种,unicode, utf-16
    print ''.join([s if isinstance(s, unicode) else s.decode('utf-16') for s in a])

    如果包含更多编码的情况,那只能一个一个猜了,可以用chardet这个库
    lixia625
        2
    lixia625  
    OP
       2015-07-15 19:59:50 +08:00
    @ayang23
    嗯 感觉也没有其他好办法了 只能一下下判断
    每次遇到这python中文编码坑就想骂娘
    magicyu1986
        3
    magicyu1986  
       2015-07-15 23:04:18 +08:00
    之前也遇到过这个问题。
    遍历可能的字符编码,然后用正则表达式一个一个的匹配。
    这种方式,笨,慢,期待其他高人的回答。
    Hackathon
        4
    Hackathon  
       2015-07-16 01:35:31 +08:00   ❤️ 1
    In [9]: from CodeConvert import CodeConvert as cc

    In [10]: a = [u'\u54c8\u54c8', '\xba\xc7\xba\xc7']

    In [11]: ''.join(cc.Convert2Unicode(a))
    Out[11]: u'\u54c8\u54c8\u5475\u5475'

    In [12]:

    CodeConvert 只考虑了部分编码,大部分情况下还是够用的
    wkdhf233
        5
    wkdhf233  
       2015-07-16 02:52:11 +08:00
    你可以把猜编码的函数都丢一个list里,猜中的朝前移。。
    huangfs
        6
    huangfs  
       2015-07-16 09:00:55 +08:00
    python3?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3919 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 00:52 · PVG 08:52 · LAX 17:52 · JFK 20:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.