Python 脚本无法正确编码特殊的 Unicode 字符

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

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

早上好,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

最佳答案

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

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

基本上,正如文档所说:

If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.

关于Python 脚本无法正确编码特殊的 Unicode 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59112449/

相关文章:

python - 问题涉及WSL、Gunicorn、Docker和Flask

python - 如何使用 lxml 创建文本节点?

c++ - PCRE2 UTF32 用法

c++ - 如何将 Unicode 字符串转换为 utf-8 或 utf-16 字符串?

python - 如何通过描述性名称查找 unicode 字符?

java - Unix 上的 utf-8 问题

python - 如何告诉 Django,memcached 运行时项目大小大于默认值?

python - python中sqlite的SQL错误

xml - XSLT/XML : convert apostrophe to a specific entity string

io - Perl6 (Rakudo) - 如何处理文件中的特殊字符?