首页 > 解决方案 > Python UTF8 编码 2.7.5 / 3.8.5

问题描述

我试图理解的是我在 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

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

标签: pythonpython-3.xpython-2.7utf-8character-encoding

解决方案


最可能的问题是从 json 对象加载的值是unicode而不是str. 在 Python 2unicode中相当于str在 Python 3 中,而 Python 2str相当于在 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 2str尝试编码u"Vunk-Gerät"为 ascii,但它不能(因为“ä”)。

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

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

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

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


推荐阅读