python 2.7.8 中如何将dict 写入非英文字符的文件?

How to write dict into file with characters other than English letters in python 2.7.8?

这是一个简单的例子:

test = {'location': '北京', 'country': '中国'}  # the values are Chinese.  

在文件 test.log 中:

{'location': '北京', 'country': '中国'} 

在python2.7.8中,当我需要输出数据时,我使用str()方法。

file_out = open('test.log', 'w')
file_out.write(str(test))
file_out.close()
当 dict 包含其他字符时,

str() 方法不起作用。我知道在python2中默认是ASCII,这个不支持中文。

我的问题是如何将字典输出到文件中?有人给我提了Json包,但是我不知道怎么用。

这就是你想要的。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import json
ori_test = {'location': '北京', 'country': '中国'}
test = dict([(unicode(k, "utf-8"), unicode(v, "utf-8")) for k, v in ori_test.items()])

my_dict = json.dumps(test, ensure_ascii=False).encode('utf8')
print my_dict
# then write my_dict to the local file as you want

这篇 link 可能对您有所帮助。

填充此结构的代码应生成 Unicode 字符串(Python 2 u"..." 字符串),而不是字节字符串(Python 2 "..." 字符串)。看 http://nedbatchelder.com/text/unipain.html 以很好地介绍这两种数据类型之间的相关差异。

基于(早期版本)m170897017 的回答;

#!/usr/bin/python
# -*- coding: utf-8 -*-

import json
test = {u'location': u'北京', u'country': u'中国'}
my_json = json.dumps(test, ensure_ascii=False).encode('utf8')
print my_json

如果您有以编程方式填充 location 字段的代码,请使用 Unicode 字符串填充它。例如,如果您从某处读取 UTF-8 数据,decode() 在将它放在那里之前。

def update_location ():
    location = '北京'
    return location.decode('utf-8')

test['location'] = update_location()

除了 JSON 之外,您还可以使用其他序列化格式,包括 Python 结构的 str() 表示,但 JSON 是标准的、定义明确的和良好的-记录在案。它要求所有字符串都是 UTF-8,因此它对非英语字符串很有效。

Python2 在内部使用字节字符串或 Unicode 字符串,但在这种情况下,应着重推荐 Unicode 字符串,它将是您移动到 ​​[=] 的唯一明智选择 if/when 28=]3。尽快将所有内容转换为 Unicode,并仅在必要时才转换(返回?)为外部表示形式(例如 UTF-8)。