【发布时间】: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) -
也许你需要不同的编码 - 即。
latin2、cp1250、cp1251、cp1252等、iso8859-2等 - 某些字符可能具有不同编码的相同代码。见表Standard Encodings
标签: python unicode character-encoding special-characters python-unicode