我想获得一个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'
Run Code Online (Sandbox Code Playgroud)
任何想法如何解决这个问题?解决方案不必看起来像这样.任何给我在unicode中缩写月份名称的解决方案都很好.
Den*_*ach 12
更改代码中的最后一行:
>>> print calendar.month_abbr[6].decode("utf8")
???
Run Code Online (Sandbox Code Playgroud)
repr()你已经得到了所需要的不正当使用的隐藏物.
也getlocale()可用于获取当前语言环境的编码:
>>> locale.setlocale(locale.LC_ALL, 'en_US')
'en_US'
>>> locale.getlocale()
('en_US', 'ISO8859-1')
Run Code Online (Sandbox Code Playgroud)
另一个可能对您有用的模块:
locale根据操作系统中的语言环境数据库生成初始或变形的月份名称(因此您不能依赖于俄语这样的语言!)并使用一些编码,但是PyICU对于初始和变形形式有不同的格式说明符(所以你可以选择适合您的情况)并使用unicode.locale限制的解决方法.