gpt4 book ai didi

Python JSON 保留编码

转载 作者:太空宇宙 更新时间:2023-11-04 08:15:32 25 4
gpt4 key购买 nike

我有这样一个文件:

aarónico
aaronita
ababol
abacá
abacería
abacero
ábaco
#more words, with no ascii chars

当我读取该文件并将其打印到控制台时,它的打印结果与预期完全相同,但是当我这样做时:

f.write(json.dumps({word: Lookup(line)}))

改为保存:

{"aar\u00f3nico": ["Stuff"]}

当我期望的时候:

{"aarónico": ["Stuff"]}

当我使用 jason.loads() 时,我需要得到相同的结果,但我不知道在哪里或如何进行编码,或者是否需要它才能让它工作。

编辑

这是将数据保存到文件的代码:

with open(LEMARIO_FILE, "r") as flemario:
with open(DATA_FILE, "w") as f:
while True:
word = flemario.readline().strip()
if word == "":
break
print word #this is correct
f.write(json.dumps({word: RAELookup(word)}))
f.write("\n")

这个加载数据并返回字典对象:

    with open(DATA_FILE, "r") as f:
while True:
new = f.readline().strip()
if new == "":
break
print json.loads(new) #this is not

如果键值与保存的键值不同,我将无法查找字典。

编辑 2

>>> import json
>>> f = open("test", "w")
>>> f.write(json.dumps({"héllö": ["stuff"]}))
>>> f.close()
>>> f = open("test", "r")
>>> print json.loads(f.read())
{u'h\xe9ll\xf6': [u'stuff']}
>>> "héllö" in {u'h\xe9ll\xf6': [u'stuff']}
False

最佳答案

这是正常且有效的 JSON 行为。 Python 也使用 \uxxxx 转义符,因此请确保不要将 python 文字表示与字符串内容混淆。

Python 3.3 中的演示:

>>> import json
>>> print('aar\u00f3nico')
aarónico
>>> print(json.dumps('aar\u00f3nico'))
"aar\u00f3nico"
>>> print(json.loads(json.dumps('aar\u00f3nico')))
aarónico

在 python 2.7 中:

>>> import json
>>> print u'aar\u00f3nico'
aarónico
>>> print(json.dumps(u'aar\u00f3nico'))
"aar\u00f3nico"
>>> print(json.loads(json.dumps(u'aar\u00f3nico')))
aarónico

当从文件读取和写入文件时,以及仅指定原始字节字符串("héllö" 是原始字节字符串)时,您处理Unicode 数据。您需要先了解编码数据和 Unicode 数据之间的区别。我强烈建议您至少阅读以下 3 篇文章中的 2 篇:

你很幸运,你的 "héllö" python 原始字节字符串表示,Python 设法自动为你解码。从文件中读回的值是完全正常和正确的:

>>> print u'h\xe9ll\xf6'
héllö

关于Python JSON 保留编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15184621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com