繁体   English   中英

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

[英]How to get unicode month name in Python?

我想获得一个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中缩写月份名称的解决方案都很好。

更改代码中的最后一行:

>>> 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限制的解决方法。

你需要的是:

…
myencoding= locale.getpreferredencoding()
print repr(calendar.month_abbr[6].decode(myencoding))
…

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM