gcq*_*gcq 1 python encoding json
我有这样一个文件:
aarónico
aaronita
ababol
abacá
abacería
abacero
ábaco
#more words, with no ascii chars
Run Code Online (Sandbox Code Playgroud)
当我将该文件读取并打印到控制台时,它会按预期打印完全相同,但是当我这样做时:
f.write(json.dumps({word: Lookup(line)}))
Run Code Online (Sandbox Code Playgroud)
这保存了:
{"aar\u00f3nico": ["Stuff"]}
Run Code Online (Sandbox Code Playgroud)
当我预料到:
{"aarónico": ["Stuff"]}
Run Code Online (Sandbox Code Playgroud)
当我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")
Run Code Online (Sandbox Code Playgroud)
这个加载数据并返回字典对象:
with open(DATA_FILE, "r") as f:
while True:
new = f.readline().strip()
if new == "":
break
print json.loads(new) #this is not
Run Code Online (Sandbox Code Playgroud)
如果密钥与保存的密钥不同,我无法查找字典.
编辑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
Run Code Online (Sandbox Code Playgroud)
这是正常且有效的JSON行为.该\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
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
从文件读取和写入文件时,以及仅指定原始字节字符串(并且"héllö"是原始字节字符串)时,您不处理Unicode数据.您需要首先了解编码和Unicode数据之间的差异.我强烈建议您阅读以下3篇文章中的至少2篇:
Ned Batchelder的实用Unicode
绝对最低每个软件开发人员绝对必须知道关于Unicode和字符集(没有任何借口!)作者:Joel Spolsky
你很幸运,你的"héllö"python原始字节字符串表示,Python设法自动解码它.从文件中读回的值完全正常且正确:
>>> print u'h\xe9ll\xf6'
héllö
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
759 次 |
| 最近记录: |