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
vtoexsir
V2EX  ›  Python

python 中怎么判断编码的兼容性?

  •  
  •   vtoexsir · 2016-10-05 18:10:30 +08:00 · 2400 次点击
    这是一个创建于 2766 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在 python 中,strjoin=str1+str2,如果 str1(ascii 编码)和 str2(utf-8 编码)的编码方式不一致,比如,那么 strjoin 将是个'奇怪的字符串',自身就有两种不同的编码. 这种情况往往导致 strjoin 显示为乱码. 在 ruby 中,当执行 strjoin=str1+str2 时,ruby 会检验 str1 编码和 str2 的编码,以及这两个编码是否兼容(例如,utf-8 编码就可以兼容 ascii 编码),如果兼容,就统一使用兼容性的编码作为 strjoin 的编码. 检查编码兼容性的伪代码如下:

    Encoding.compatible?(coding1, coding2)

    如果 coding1 兼容 coding2 编码,则返回 coding1;如果 coding2 兼容 coding1,则返回 coding2;如果 coding1 和 coding2 没有兼容性,则返回 false.

    我想问的是,python 中是否有类似的方法或者模块,来检查编码的兼容性? 多谢!

    7 条回复    2016-10-06 04:38:40 +08:00
    jimzhong
        1
    jimzhong  
       2016-10-05 18:44:21 +08:00
    python3 里面 str 采用 unicode 存储,不存在编码问题。
    binux
        2
    binux  
       2016-10-05 18:53:59 +08:00
    这是一个 xy 问题,你理解错了
    1. python 中(我理解你使用的 python2 ) str 是 bytes 类型,对编码无感知。
    2. ascii 是 utf8 的子集,即使 strjoin ,也不存在两种不同的编码一说
    3. 显示为乱码,与「编码兼容」无关。而是你终端编码和输出编码不同。
    ethego
        3
    ethego  
       2016-10-05 19:09:45 +08:00 via iPhone
    这和 Python 对编码的处理无关, utf8 本来就是兼容 ascii 的,单纯的拼接不会造成乱码
    gdsing
        4
    gdsing  
       2016-10-05 21:23:58 +08:00   ❤️ 1
    楼主举了一个不是太好的例子,根据楼主的意思,提供:

    str1 = u'中文'.encode('gbk')

    str2 = u'中文'.encode('utf-8')

    print str1 + str2
    ����中文
    justou
        5
    justou  
       2016-10-05 21:35:53 +08:00 via Android
    没有任何有效算法来判断字符串的编码。可以使用统计的方法估计编码,比如 chardet ,既然是统计,那对小样本几乎是无效的。同理,要判断两个较短的字符串是否为相同编码不大可能。如果有有效方法请纠正我。
    billlee
        6
    billlee  
       2016-10-05 22:00:38 +08:00   ❤️ 1
    先把 str(py2)/bytes(py3k) decode 成 unicode(py2)/str(py3k), 再拼接
    haoc
        7
    haoc  
       2016-10-06 04:38:40 +08:00
    print 乱码可能是 console 自己不支持。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1734 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 00:28 · PVG 08:28 · LAX 17:28 · JFK 20:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.