推荐学习书目
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 · Jul 15, 2015 · 3263 views
    This topic created in 3965 days ago, the information mentioned may be changed or developed.


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

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

    6 replies    2015-07-16 09:00:55 +08:00
    ayang23
        1
    ayang23  
       Jul 15, 2015   ❤️ 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
       Jul 15, 2015
    @ayang23
    嗯 感觉也没有其他好办法了 只能一下下判断
    每次遇到这python中文编码坑就想骂娘
    magicyu1986
        3
    magicyu1986  
       Jul 15, 2015
    之前也遇到过这个问题。
    遍历可能的字符编码,然后用正则表达式一个一个的匹配。
    这种方式,笨,慢,期待其他高人的回答。
    Hackathon
        4
    Hackathon  
       Jul 16, 2015   ❤️ 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  
       Jul 16, 2015
    你可以把猜编码的函数都丢一个list里,猜中的朝前移。。
    huangfs
        6
    huangfs  
       Jul 16, 2015
    python3?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   872 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 22:04 · PVG 06:04 · LAX 15:04 · JFK 18:04
    ♥ Do have faith in what you're doing.