Сав*_*сим 2 arrays unicode dictionary
#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\n\nd = {'a':'\xd1\x82\xd0\xb5\xd0\xba\xd1\x81\xd1\x82',\n 'b':{\n 'a':'\xd1\x82\xd0\xb5\xd0\xba\xd1\x81\xd1\x822',\n 'b':'\xd1\x82\xd0\xb5\xd0\xba\xd1\x81\xd1\x823'\n }}\nprint(d)\n\nw = open('log', 'w')\njson.dump(d,w, ensure_ascii=False)\nw.close()\n
Run Code Online (Sandbox Code Playgroud)\n\n它给了我:\nUnicodeEncodeError: 'ascii' 编解码器无法对位置 1-5 中的字符进行编码:序数不在范围内(128)
\n发布完整的回溯,当无法解码字典对象时,错误可能来自打印语句。由于某种原因,如果其中包含西里尔文本,则 print 语句无法解码所有内容。
\n\n以下是我将包含西里尔字母的字典保存到 json 的方法:
\n\nmydictionary = {\'a\':\'\xd1\x82\xd0\xb5\xd0\xba\xd1\x81\xd1\x82\'}\nfilename = "myoutfile"\nwith open(filename, \'w\') as jsonfile:\n json.dump(mydictionary, jsonfile, ensure_ascii=False)\n
Run Code Online (Sandbox Code Playgroud)\n\n诀窍是将 json 读回字典并用它做事。
\n\n要将 json 读回到字典中:
\n\nwith open(filename, \'r\') as jsonfile: \nnewdictonary = json.load(jsonfile)\n
Run Code Online (Sandbox Code Playgroud)\n\n现在,当您查看字典时,单词 \'\xd1\x82\xd0\xb5\xd0\xba\xd1\x81\xd1\x82\' 看起来(编码)为 \'\\u0442\\u0435\\u043a \\u0441\\u0442\'。您只需要使用encode(\'utf-8\')对其进行解码:
\n\nfor key, value in newdictionary.iteritems():\n print value.encode(\'utf-8\')\n
Run Code Online (Sandbox Code Playgroud)\n\n如果您的西里尔文文本存储在列表中,则同样适用:
\n\nfor f in value:\n print f.encode(\'utf-8\')\n # or if you plan to use the val somewhere else:\n f = f.encode(\'utf-8\')\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
5368 次 |
最近记录: |