加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 12:15:58 所属栏目:Python 来源:网络整理
导读:我想获得一个unicode版本的calendar.month_abbr [6].如果我没有为语言环境指定编码,我不知道如何将字符串转换为unicode.下面的示例代码显示了我的问题: import locale import calendar locale.setlocale(locale.LC_ALL,("ru_RU"))'ru_RU' print repr(calend
我想获得一个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])
'xb8xeexdd'
>>> 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])
'xd0x98xd1x8exd0xbd'
>>> print repr(calendar.month_abbr[6].decode("utf8"))
u'u0418u044eu043d'

任何想法如何解决这个问题?解决方案不必看起来像这样.任何给我在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 – 一套使用俄语的工具,包括日期.它具有硬编码的月份名称作为区域设置限制的解决方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读