2009-11-30 43 views
3

我想要得到一个unicode版本的calendar.month_abbr[6]。如果我没有指定区域设置的编码,我不知道如何将字符串转换为unicode。下面的示例代码显示我的问题:如何在Python中获取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缩写月份名称是好的。

回答

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

如果Unicode转换成功,我应该还是能够做到就可以了再版。所以这不应该是问题。感谢您的链接。我会检查出来。 – 2009-11-30 19:06:51

+0

'locale.getlocale()'工作。谢谢。 – 2009-12-01 18:57:55

0

你需要的是:

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

在我的机器上'locale.getpreferredencoding()'返回utf8。所以我仍然有同样的问题。 – 2009-12-01 09:12:00

+1

它似乎不像'locale.getpreferredencoding()'返回'month_abbr'名称编码的编码。 – 2009-12-01 09:15:55