gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:29:47 25 4
gpt4 key购买 nike

我正在尝试获取 calendar.month_abbr[6] 的 unicode 版本。如果我没有为语言环境指定编码,我不知道如何将字符串转换为 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')

可能对您有用的其他模块:

  • PyICU - 更好的国际化方式。虽然 locale 根据操作系统中的区域设置数据库生成月份名称的初始形式或变形形式(因此你不能依赖它来处理像俄语这样的语言!)并使用一些编码,PyICU 对初始形式和变形形式有不同的格式说明符(因此您可以根据自己的情况选择合适的)并使用 unicode。
  • pytils - 一套使用俄语的工具,包括日期。它有硬编码的月份名称作为 locale 限制的解决方法。

关于python - 如何在 Python 中获取 unicode 月份名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1821204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com