【问题标题】:Python UTF8 encoding 2.7.5 / 3.8.5Python UTF8 编码 2.7.5 / 3.8.5
【发布时间】:2020-12-17 23:52:24
【问题描述】:

我试图理解的是,我在 Windows 上运行 Python 3.8.5,在我的网络服务器上运行 Python 2.7.5。

我正在尝试使用这样的代码从 JSON 进行翻译

hash = ""
try:
    hash = str(translateTable[item["hash"]])
except:
hash = str(item["hash"])

以下代码正在加载 JSON 文件

with io.open('translate.json', encoding="utf-8") as fh:
    translateTable = json.load(fh)

JSON FILE {"vunk": "Vunk-Gerät"}

当我在 3.7.5 的 windows 上运行代码时,结果应该是这样的

IN >>> python test.py
OUT>>> Vunk-Gerät

棘手的部分来了,当我使用 Python 2.7.5 在我的网络服务器上运行时,结果是这样的

IN >>> python test.py
OUT>>> vunk

问题是,在网络服务器上它不能翻译“Ä,Ö,Ü,ß”,我不明白为什么?

【问题讨论】:

  • 我说的问题只是在 Python 2.7.5 Webserver 上。在 Windows 上它可以正常工作,这是我在每个站点上使用相同代码时所没有的。
  • Python 2.7 自 2020 年 1 月(2008 年宣布)起停止使用和停止支持。您正在使用软件比您打算运行的软件提前 12 年进行开发。请使用 python 3.x,不要让你的生活苦苦追寻 12 年前的 bug 修复。

标签: python python-3.x python-2.7 utf-8 character-encoding


【解决方案1】:

最可能的问题是从 json 对象加载的值是 unicode 而不是 str。在 Python 2 中,unicode 相当于 Python 3 中的 str,而 Python 2 的 str 相当于 Python 3 的 bytes。所以问题可能是:

transtable = {u"vunk": u"Vunk-Gerät"}

str(transtable['vunk'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 8: ordinal not in range(128)

发生这种情况是因为 Python 2 的 str 尝试将 u"Vunk-Gerät" 编码为 ascii,但它不能(因为“ä”)。

最简单的解决方案可能是完全避免调用str

hash = ""
try:
    hash = translateTable[item["hash"]]
except Exception as ex:
    hash = item["hash"]

因为键和值应该可以按原样使用。

一种更强大的方法是使用six 库以适用于 Python 2 和 Python 3 的方式处理字符串和字节类型。正如其他人指出的那样,理想的解决方案是运行 Python 3在您的服务器上。在处理非 ASCII 文本时,Python 3 更容易使用。

【讨论】:

  • 感谢您的回答,但不使用 str() 的问题会导致我出现与您已经发布的相同的错误。
  • 这是因为在使用 Python 2 处理非 ASCII 字符串时很可能会发生此错误,除非应用程序从一开始就考虑到这一目标。本质上,应尽可能避免在 Python 2 中使用str,通常采用“unicode 三明治”技术。开发人员需要注意 Python 2 隐式编码值的情况。无论如何,很高兴您找到了解决问题的方法。
【解决方案2】:

对于和我遇到同样问题的人来说,这里是 2.7.5 的解决方案

from django.utils.six import smart_str, smart_unicode
hash = ""
try:
    hash = smart_str(translateTable[item["hash"]])
except Exception as ex:
    hash = smart_str(item["hash"])

还要确保已安装 django

pip install django

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 2013-06-11
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多