[英]Python script failing to correctly encode special Unicode characters
我正在转换一个文本文件( words.txt
),它基本上是这种格式的字典:
good morning, Góðan daginn
转换成这种格式的 json 文件( converted.json
)
{
"wordId": 1,
"word": "good morning",
"translation": "Góðan daginn"
}
从文本文件到 json 文件的转换完全正常,并且符合预期,但字符编码有点混乱,方法如下:
为了编码这个字符ð
而不是这样做\ð
脚本像这样编码那个字符: \Ã\°
问题:如何修复和/或调整脚本以正确编码这些特殊字符? 请记住,这些字符主要是冰岛语/斯堪的纳维亚语,我使用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))
所以基本上,正如文件所说:
如果 ensure_ascii 为真(默认值),则输出保证所有传入的非 ASCII 字符都被转义。 如果 ensure_ascii 为 false,则这些字符将按原样输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.