gpt4 book ai didi

python - Python 和 gettext 的 UTF-8 错误

转载 作者:太空狗 更新时间:2023-10-29 22:08:27 24 4
gpt4 key购买 nike

我在我的编辑器中使用 UTF-8,所以这里显示的所有字符串在文件中都是 UTF-8。

我有一个像这样的 python 脚本:

# -*- coding: utf-8 -*-
...
parser = optparse.OptionParser(
description=_('automates the dice rolling in the classic game "risk"'),
usage=_("usage: %prog attacking defending"))

然后我用 xgettext 把所有东西都拿出来,得到一个 .pot 文件,它可以归结为:

"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"

#: auto_dice.py:16
msgid "automates the dice rolling in the classic game \"risk\""
msgstr ""

之后,我使用 msginit 得到了一个 de.po,我这样填写:

"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

#: auto_dice.py:16
msgid "automates the dice rolling in the classic game \"risk\""
msgstr "automatisiert das Würfeln bei \"Risiko\""

运行脚本,出现以下错误:

  File "/usr/lib/python2.6/optparse.py", line 1664, in print_help
file.write(self.format_help().encode(encoding, "replace"))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 60: ordinal not in range(128)

我该如何解决?

最佳答案

该错误意味着您在字节串上调用了编码,因此它会尝试使用系统默认编码(Python 2 上的 ascii)将其解码为 Unicode,然后使用您指定的任何内容重新编码。

通常,解决它的方法是在尝试使用字符串之前调用 s.decode('utf-8')(或字符串所在的任何编码)。如果您只使用 unicode 文字,它也可能有效:u'automates...'(这取决于如何从 .po 文件中替换字符串,我不知道)。

这种令人困惑的行为在 Python 3 中得到了改进,它不会尝试将字节转换为 unicode,除非您明确告诉它。

关于python - Python 和 gettext 的 UTF-8 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5545197/

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