【问题标题】:Does python support unicode beyond basic multilingual plane?python是否支持基本多语言平面之外的unicode?
【发布时间】:2013-10-23 16:28:06
【问题描述】:

下面是一个简单的测试。 repr 似乎工作正常。然而 lenx for x in 在 Python 2.6 和 2.7 中似乎没有正确划分 unicode 文本:

In [1]: u"????????"
Out[1]: u'\U0002f920\U0002f921'

In [2]: [x for x in u"????????"]
Out[2]: [u'\ud87e', u'\udd20', u'\ud87e', u'\udd21']

好消息是 Python 3.3 做了正确的事™。

Python 2.x 系列还有希望吗?

【问题讨论】:

    标签: python python-2.7 unicode


    【解决方案1】:

    可以,前提是您编译的 Python 支持宽 unicode。

    默认情况下,Python 仅使用窄 unicode 支持构建。启用广泛的支持:

    ./configure --enable-unicode=ucs4
    

    您可以通过测试sys.maxunicode来验证使用了什么配置:

    import sys
    if sys.maxunicode == 0x10FFFF:
        print 'Python built with UCS4 (wide unicode) support'
    else:
        print 'Python built with UCS2 (narrow unicode) support'
    

    广泛的构建将使用 UCS4 字符作为 所有 unicode 值,使这些值的内存使用量增加一倍。 Python 3.3 切换到可变宽度值;只有足够的字节用于表示当前值中的所有字符。

    快速演示显示宽版本正确处理您的示例 Unicode 字符串:

    $ python2.6
    Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) 
    [GCC 4.4.5] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import sys
    >>> sys.maxunicode
    1114111
    >>> [x for x in u'\U0002f920\U0002f921']
    [u'\U0002f920', u'\U0002f921']
    

    【讨论】:

    • 3.3 使用哪种编码?
    • @DavidHeffernan:见PEP 393;直到 UCS4,如果所有字符的 2 个 LSB 字节为 0,则下降到 UCS2,如果所有字符的剩余 LSB 为 0,则下降到 Latin-1。
    • 谢谢。看起来很狂野。维护字符串的并行副本。有趣的是,他们选择了负载依赖编码。
    • @qarma:Python 3.3 完全取消了窄与宽,因此sys.maxunicode 在那里被硬编码为 0x10ffff。 OS X 捆绑的 Python 版本都很窄。
    • @HerrKaputt:很好发现。现已更正!
    猜你喜欢
    • 2011-12-13
    • 2012-04-03
    • 2018-02-03
    • 2018-01-22
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 2011-05-01
    相关资源
    最近更新 更多