![](/img/trans.png)
[英]How to parse unicode month name to get datetime in Python 2.7
[英]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')
另一个可能对您有用的模块:
你需要的是:
…
myencoding= locale.getpreferredencoding()
print repr(calendar.month_abbr[6].decode(myencoding))
…
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.