【问题标题】:Python script failing to correctly encode special Unicode charactersPython 脚本未能正确编码特殊的 Unicode 字符
【发布时间】:2023-03-11 20:28:01
【问题描述】:

我正在转换一个文本文件 (words.txt),它基本上是这种格式的字典:

good morning, Góðan daginn

以这种格式写入一个 json 文件 (converted.json)

{
    "wordId": 1,
    "word": "good morning",
    "translation": "Góðan daginn"
}

从文本文件到 json 文件的转换工作正常,符合预期,但字符编码有点混乱,方法如下:

为了编码这个字符 ð 而不是这样做 \u00f0 脚本像这样编码那个字符:\u00c3\u00b0

问题:如何修复和/或调整脚本以正确编码这些特殊字符?请记住,这些字符主要是冰岛语/斯堪的纳维亚语,我使用 PyCharm 作为 IDE

PS请注意我的Python技能有点有限!!

这是脚本converter.py

import json

with open('words.txt', 'r') as f_in, \
    open('converted.json', 'w') as f_out:
cnt = 1
data = []
for line in f_in:
    line = line.split(',')
    if len(line) != 2:
        continue
    d = {"wordId": cnt, "word": line[0].strip(), "translation": line[1].strip()}
    data.append(d)
    cnt += 1

f_out.write(json.dumps(data, indent=4))

我正在使用 Python 3

【问题讨论】:

  • 如果这是 Python 2,您需要使用 .decode('utf-8') 解码文件中的字符串,否则您将获得原始字节字符串。 (Python 3 可以防止你犯这个错误 - 强烈建议为任何新代码升级到 Python 3!)
  • @nneonneo 我刚刚尝试使用 Python 3 和 Jupyter,但仍然得到相同的错误结果!我还能做什么?
  • Python 作为默认使用 UTF-8ð 在 utf-8 有代码 \u00c3\u00b0。它在Latin-1 中有代码\u00f0 参见print( 'ð'.encode('latin-1') )
  • @furas 我试过这个"translation": line[1].strip().encode('latin-1') 但我得到了以下错误:UnicodeEncodeError: 'latin-1' codec can't encode character '\u201c' in position 2: ordinal not in range(256)
  • 也许你需要不同的编码 - 即。 latin2cp1250cp1251cp1252 等、iso8859-2 等 - 某些字符可能具有不同编码的相同代码。见表Standard Encodings

标签: python unicode character-encoding special-characters python-unicode


【解决方案1】:

我认为问题在于json.dumps,您可能需要使用ensure_ascii=False。喜欢:

f_out.write(json.dumps(data, indent=4, ensure_ascii=False))

所以基本上,正如文件所说:

如果 ensure_ascii 为真(默认),则保证输出 转义所有传入的非 ASCII 字符。如果 ensure_ascii 是 false,这些字符将按原样输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-18
    • 2012-05-17
    • 1970-01-01
    • 2016-10-19
    • 2013-06-07
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    相关资源
    最近更新 更多