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

问题描述 投票:0回答:1

我正在转换文本文件(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 unicode character-encoding special-characters python-unicode
1个回答
0
投票

我相信问题是json.dumps,您可能需要使用ensure_ascii=False。喜欢:

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

基本上,如文件所述:

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

© www.soinside.com 2019 - 2024. All rights reserved.