如何在Python中获取unicode月份名称?
我正在尝试获取日历.month\u abbr[6]的unicode版本。如果我没有为区域设置指定编码,我就不知道如何将字符串转换为unicode。下面的示例代码显示了我的问题:如何在Python中获取unicode月份名称?,python,unicode,Python,Unicode,我正在尝试获取日历.month\u abbr[6]的unicode版本。如果我没有为区域设置指定编码,我就不知道如何将字符串转换为unicode。下面的示例代码显示了我的问题: >>> import locale >>> import calendar >>> locale.setlocale(locale.LC_ALL, ("ru_RU")) 'ru_RU' >>> print repr(calendar.month_ab
>>> 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'
导入区域设置
>>>导入日历
>>>setlocale(locale.LC_ALL,(“ru_-ru”))
“汝汝”
>>>打印报告(日历月份缩写[6])
“\xb8\xee\xdd”
>>>打印报告(日历.月份缩写[6].解码(“utf8”))
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/usr/lib/python2.5/encodings/utf_8.py”,第16行,解码
返回编解码器.utf_8_解码(输入,错误,真)
UnicodeDecodeError:“utf8”编解码器无法解码位置0中的字节0xb8:意外的代码字节
>>>setlocale(locale.LC_ALL,(“ru_ru”,“utf8”))
“ru_ru.UTF8”
>>>打印报告(日历月份缩写[6])
“\xd0\x98\xd1\x8e\xd0\xbd”
>>>打印报告(日历.月份缩写[6].解码(“utf8”))
u'\u0418\u044e\u043d'
有什么办法解决这个问题吗?解决方案不必像这样。任何用unicode为我提供缩写月份名称的解决方案都可以。更改代码中的最后一行:
>>> print calendar.month_abbr[6].decode("utf8")
Июн
如果使用不当,你就不会知道你已经得到了你所需要的
还可以使用getlocale()
获取当前区域设置的编码:
>>> locale.setlocale(locale.LC_ALL, 'en_US')
'en_US'
>>> locale.getlocale()
('en_US', 'ISO8859-1')
其他可能对您有用的模块:
- -更好的国际化方式。虽然
根据操作系统中的locale数据库生成月名的首字母或屈折形式(因此,对于俄语等语言,您不能依赖它!)并使用一些编码,locale
对首字母和屈折形式有不同的格式说明符(因此您可以根据自己的情况选择适当的格式)并使用unicodePyICU
- -一套使用俄语的工具,包括日期。它有硬编码的月份名称作为
限制的解决方法locale
- 您需要的是:
…
myencoding= locale.getpreferredencoding()
print repr(calendar.month_abbr[6].decode(myencoding))
…
如果unicode转换成功,我仍然可以对它进行一次报告。所以这不应该是问题所在。谢谢你的链接。我将检查它们。在我的计算机上
locale.getpreferredencoding()
返回utf8。所以我仍然有同样的问题。它看起来不像是locale.getpreferredencoding()
返回month\u abbr
名称的编码。