如何在Python中获取Unicode月份名称?

3

我正在尝试获取一个unicode版本的calendar.month_abbr[6]。如果我不为本地化指定编码,我不知道如何将字符串转换为unicode。下面的示例代码显示了我的问题:

>>> import locale
>>> import calendar
>>> locale.setlocale(locale.LC_ALL, ("ru_RU"))
'ru_RU'
>>> print repr(calendar.month_abbr[6])
'\xb8\xee\xdd'
>>> print repr(calendar.month_abbr[6].decode("utf8"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8 in position 0: unexpected code byte
>>> locale.setlocale(locale.LC_ALL, ("ru_RU", "utf8"))
'ru_RU.UTF8'
>>> print repr(calendar.month_abbr[6])
'\xd0\x98\xd1\x8e\xd0\xbd'
>>> print repr(calendar.month_abbr[6].decode("utf8"))
u'\u0418\u044e\u043d'

有什么解决方法吗?解决方案不一定要像这样。只要能给我提供Unicode缩写月份名称的任何解决方案都可以。
2个回答

12

更改代码中的最后一行:

>>> print calendar.month_abbr[6].decode("utf8")
Июн

不正确地使用 repr() 会使你无法看到你已经得到了所需的结果。

getlocale() 还可以用来获取当前区域设置的编码:

>>> locale.setlocale(locale.LC_ALL, 'en_US')
'en_US'
>>> locale.getlocale()
('en_US', 'ISO8859-1')

以下是可能对您有用的其他模块:

  • PyICU - 一个更好的国际化方式。虽然 locale 在您的操作系统的语言数据库中仅生成月份名称的初始形式或屈折形式(因此您不能在俄语等语言的情况下依赖它!)并使用某些编码, PyICU 具有针对初始和屈折形式的不同格式说明符(因此您可以选择适当的说明符),并使用Unicode。
  • pytils - 一组用于处理俄语的工具,包括日期。它通过硬编码月份名称来解决 locale 的限制。

如果Unicode转换成功,我仍然应该能够对其进行repr。所以那不应该是问题。感谢提供的链接。我会查看它们。 - Rickard Lindberg

0
你需要的是:
…
myencoding= locale.getpreferredencoding()
print repr(calendar.month_abbr[6].decode(myencoding))
…

在我的电脑上,locale.getpreferredencoding() 返回 utf8。所以我仍然有同样的问题。 - Rickard Lindberg
1
似乎 locale.getpreferredencoding() 不会返回 month_abbr 名称所编码的编码方式。 - Rickard Lindberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接