在python 下面一个包含中文字符串的列表(list)或字典,直接使用print会出现以下的结果:
dict = {\”asdf\”: \”我们的python学习\”}
print dict
{\’asdf\’: \’\\xe6\\x88\\x91\\xe4\\xbb\\xac\\xe7\\x9a\\x84python\\xe5\\xad\\xa6\\xe4\\xb9\\xa0\’}
在输出处理好的数据结构的时候很不方便,需要使用以下方法进行输出:
import json
print json.dumps(dict, encoding=\”UTF-8\”, ensure_ascii=False)
{\”asdf\”: \”我们的python学习\”}
注意上面的两个参数
要是已经有dict,还好。我是从mongo中拿,所以需要Json.loads,但总是有问题。所以这个方案不适合我。
如果是字符串,直接输出或者
print str.encode(\”UTF-8\”)
对于其他的编码同样使用。赶快试试吧。
在编辑一个别人的方案。未经验证。
all_symptom内容
[python] view plaincopy在CODE上查看代码片派生到我的代码片
[u\’\\u773c\’, u\’\\u8179\\u90e8\’, u\’\\u4e94\\u5b98\’, u\’\\u53e3\\u8154\’, u\’\\u8179\\u90e8\’,
u\’\\u53e3\\u8154\’]
[python] view plaincopy在CODE上查看代码片派生到我的代码片
str_symptom = str(all_symptom).replace(\”u\\\’\”,\”\\\’\”)
str_symptom.decode(\”unicode-escape\”)
这个方案是我后来使用的方案,不确定效率。但是可行。
我的答案是 str_symptom.decode(\"unicode-escape\").encode(\"utf-8\"). 在用unicode解码完事后,用utf-8编码。