python - 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
问题是,在网络服务器上它不能翻译“Ä,Ö,Ü,ß”,我不明白为什么?
解决方案
最可能的问题是从 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 更容易使用。
推荐阅读
- automata - 可数字符串总是可数的吗?
- java - 是否有可能跳过 finally 块并继续使用其余代码
- css - 如何更改Angular 6材质单选按钮外部波纹颜色
- perl - perl 中的 Argon2 加密
- php - 单选按钮保存选定的值
- android - Android 透明边缘图像滑块
- cassandra - 如何使用 Cassandra DB 在二级索引上使用 order by(Sorting)
- apache-spark - spark从变量字段中为withColumn函数分配列名
- amazon-web-services - 将移动应用上传到云端,而不是 google play 或应用商店
- sql - Oracle SQL 查询以获取特定格式的输出