python - Python 2.7 中平台特定的 Unicode 语义

标签 python windows unicode utf-16

Ubuntu 11.10:

$ python
Python 2.7.2+ (default, Oct  4 2011, 20:03:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = u'\U0001f44d'
>>> len(x)
1
>>> ord(x[0])
128077

Windows 7:

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = u'\U0001f44d'
>>> len(x)
2
>>> ord(x[0])
55357

我的 Ubuntu 体验是使用发行版中的默认解释器。对于 Windows 7,我下载并安装了从 python.org 链接的推荐版本。我自己都没有编译它们。

差异的本质对我来说很清楚。 (在 Ubuntu 上,字符串是代码点序列;在 Windows 7 上,字符串是 UTF-16 代码单元序列。)我的问题是:

  • 为什么我会观察到这种行为差异?是解释器的构建方式,还是依赖的系统库不同?
  • 有什么方法可以配置 Windows 7 解释器的行为以与 Ubuntu 解释器一致,我可以在 Eclipse PyDev 中完成(我的目标)?
  • 如果我必须重建,是否有来自可靠来源的任何预构建的 Windows 7 解释器,其行为与上述 Ubuntu 相同?
  • 除了仅在 Windows 上手动计算 unicode 字符串中的代理(blech)之外,是否有任何解决此问题的方法?
  • 这是否证明错误报告是合理的?是否有可能在 2.7 中解决此类错误报告?

最佳答案

在 Ubuntu 上,你有一个 "wide" Python build其中字符串是 UTF-32/UCS-4。不幸的是,这(还)不适用于 Windows。

Windows builds will be narrow for a while based on the fact that there have been few requests for wide characters, those requests are mostly from hard-core programmers with the ability to buy their own Python and Windows itself is strongly biased towards 16-bit characters.

Python 3.3 将有 flexible string representation ,其中您无需关心 Unicode 字符串是使用 16 位还是 32 位代码单元。

在那之前,您可以使用 UTF-16 字符串获取代码点

def code_points(text):
    utf32 = text.encode('UTF-32LE')
    return struct.unpack('<{}I'.format(len(utf32) // 4), utf32)

关于python - Python 2.7 中平台特定的 Unicode 语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9934752/

相关文章:

python - 在 Python.net 应用程序中安装自定义 IMessageFilter 时出现段错误

Python:检查列表中的所有词典是否为空

python - 正则表达式:如何匹配没有连续元音的单词?

c++ - 不应该存在的随机未解析外部符号

c# - 在安装期间检测并需要 Windows QFE/补丁

python - 如何在具有 FileShare 权限的 Windows 上使用 Python 打开文件?

c++ - 字符的 UTF-8 转换

perl DBIx sqlite {sqlite_unicode=>1}?

mysql - 存储过程中非法混合排序规则 (utf8_general_ci,IMPLICIT) 和 (utf8_unicode_ci,IMPLICIT)

Python函数返回二维numpy数组中离群值的索引