【问题标题】:platform specific Unicode semantics in Python 2.7Python 2.7 中特定于平台的 Unicode 语义
【发布时间】:2012-04-13 15:40:43
【问题描述】:

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 字符串中的代理项之外,还有其他解决方法吗?
  • 这是否证明了错误报告的合理性? 2.7 中是否有可能解决此类错误报告?

【问题讨论】:

  • 我们在周六的 Python WM 上讨论了 Unicode 支持。人们说 3.3 的 IO 系统已经向后移植到 Python 2.7。现在是午夜,但明天可能会有人回复。是不是很紧急?
  • 我已经开始编写解决方法,所以不,不紧急。令人失望的是,直到 3.2,Python 中的 Unicode 字符串类型还有这样的皱纹......

标签: python windows unicode utf-16


【解决方案1】:

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

基于以下事实,Windows 版本将在一段时间内变窄 对宽字符的要求很少,这些要求大多是 来自有能力购买自己的 Python 的铁杆程序员 而且 Windows 本身强烈偏向 16 位字符。

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)

【讨论】:

    【解决方案2】:

    好问题!我最近自己掉进了这个兔子洞。

    @dan04 的回答启发我将其扩展为 unicode 子类,该子类在窄和宽 Python 2 构建中提供一致的索引、切片和 len():

    class WideUnicode(unicode):
      """String class with consistent indexing, slicing, len() on both narrow and wide Python."""
      def __init__(self, *args, **kwargs):
        super(WideUnicode, self).__init__(*args, **kwargs)
        # use UTF-32LE to avoid a byte order marker at the beginning of the string
        self.__utf32le = unicode(self).encode('utf-32le')
    
      def __len__(self):
        return len(self.__utf32le) / 4
    
      def __getitem__(self, key):
        length = len(self)
    
        if isinstance(key, int):
          if key >= length:
            raise IndexError()
          key = slice(key, key + 1)
    
        if key.stop is None:
          key.stop = length
    
        assert key.step is None
    
        return WideUnicode(self.__utf32le[key.start * 4:key.stop * 4]
                           .decode('utf-32le'))
    
      def __getslice__(self, i, j):
        return self.__getitem__(slice(i, j))
    

    open sourced here,公共领域。用法示例:

    text = WideUnicode(obj.text)
    for tag in obj.tags:
      text = WideUnicode(text[:start] + tag.text + text[end:])
    

    (simplified from this usage.)

    感谢@dan04!

    【讨论】:

      【解决方案3】:

      我主要需要准确地测试长度。因此,无论解释器是窄的还是宽的,这个函数都能正确返回任何unicode 字符串的代码点长度。如果数据在广泛构建的解释器中使用两个代理文字而不是单个 \U 样式代码点,则只要“正确”使用代理,即作为窄构建,返回的代码点长度将说明这一点解释器会使用它们。

      invoke = lambda f: f()  # trick borrowed from Node.js
      
      @invoke
      def ulen():
        testlength = len(u'\U00010000')
        assert (testlength == 1) or (testlength == 2)
        if testlength == 1:  # "wide" interpreters
          def closure(data):
            u'returns the number of Unicode code points in a unicode string'
            return len(data.encode('UTF-16BE').decode('UTF-16BE'))
        else:  # "narrow" interpreters
          def filt(c):
            ordc = ord(c)
            return (ordc >= 55296) and (ordc < 56320)
          def closure(data):
            u'returns the number of Unicode code points in a unicode string'
            return len(data) - len(filter(filt, data))
        return closure  # ulen() body is therefore different on narrow vs wide builds
      

      测试用例,通过窄和宽构建:

      class TestUlen(TestCase):
      
        def test_ulen(self):
          self.assertEquals(ulen(u'\ud83d\udc4d'), 1)
          self.assertEquals(ulen(u'\U0001F44D'), 1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-28
        • 1970-01-01
        • 1970-01-01
        • 2010-11-09
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        相关资源
        最近更新 更多