求教一下 python 读取 json 以后,输出的问题(unicode 和中文显示)

2015-07-15 22:56:03 +08:00
 cqcn1991

直接读json的话,里面的信息都会是unicode,于是找到了一个函数,可以帮忙解决转换的问题
http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-from-json-in-python)

但是,中文的显示还是不行,输出见下

def byteify(input):
    if isinstance(input, dict):
        return {byteify(key):byteify(value) for key,value in input.iteritems()}
    elif isinstance(input, list):
        return [byteify(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input
import json
from pprint import pprint
with open('C:\Users\Administrator\Desktop\movie_list_2014_v2.json') as data_file:    
    data = json.load(data_file)
parsed_data = byteify(data)
pprint(parsed_data[1]['douban_info'])

输出(部分)

'countries': ['\xe7\xbe\x8e\xe5\x9b\xbd'],
 'current_season': None,
 'directors': [{'alt': 'http://movie.douban.com/celebrity/1302444/',
                'avatars': {'large': 'http://img3.douban.com/img/celebrity/large/45953.jpg',
                            'medium': 'http://img3.douban.com/img/celebrity/medium/45953.jpg',
                            'small': 'http://img3.douban.com/img/celebrity/small/45953.jpg'},
                'id': '1302444',
                'name': '\xe5\x86\x88\xe6\x89\x8e\xe7\xbd\x97\xc2\xb7\xe6\xb4\x9b\xe4\xbd\xa9\xe5\x85\xb9-\xe5\x8a\xa0\xe5\x8b\x92\xe6\x9e\x9c'}],
 'do_count': None,
 'douban_site': '',
 'episodes_count': None,
 'genres': ['\xe6\x81\x90\xe6\x80\x96'],

想问一下,怎么让输出显示中文
我用的,是Python2.7+notebook

4123 次点击
所在节点    问与答
14 条回复
imn1
2015-07-15 23:12:09 +08:00
bytes?
应该用 string 吧?
lcqtdwj
2015-07-15 23:12:46 +08:00
unicode多好
cqcn1991
2015-07-15 23:12:47 +08:00
@imn1 你说哪个?
cqcn1991
2015-07-15 23:13:31 +08:00
@lcqtdwj 难道正常情况下不应该是显示中文么…
imn1
2015-07-15 23:19:31 +08:00
encode('utf-8') 这个返回是 bytes 类型
不熟 py2,你看别人的回复吧

另外,简体windows dos 默认是 cp936,要显示 unicode 中文,需要程序指定utf-8,运行程序前要执行 chcp 65001 把 dos 转为 utf-8 兼容
lcqtdwj
2015-07-15 23:29:14 +08:00
我觉得这是跟你的pprint有关。打印的是object的str还是repr
cqcn1991
2015-07-15 23:29:36 +08:00
@imn1 多谢。不过我这个是在Python notebook里面执行的,和dos有关系吗?
Owenjia
2015-07-15 23:36:38 +08:00
中文输出?好像要 ensure_ascii=False 才行吧。
cqcn1991
2015-07-15 23:37:56 +08:00
@Owenjia 话说你们一般都不会涉及到中文的data wrangling么…
Septembers
2015-07-15 23:42:02 +08:00
@cqcn1991 我一般不会在Windows上处理
Tiande
2015-07-15 23:43:33 +08:00
```
import sys
reload(sys)
sys.setdefaultencoding("utf-8") #更改默认编码为utf-8
```

加在最前面。

http://www.2cto.com/kf/201407/317866.html
Owenjia
2015-07-15 23:43:54 +08:00
@cqcn1991

print(json.dumps({"语言": "中文"}, ensure_ascii=False))

这样不就输出中文了么?
Sylv
2015-07-16 03:04:31 +08:00
你概念没弄清楚,并不是说 unicode 类型的字符串就无法显示中文了,json 数据用 unicode 是正确的,并不需要多此一举用 byteify 将其数据转换为 str 类型,stackoverflow 那个问题有这个需求是因为他用的其它库只接受 str 类型数据,而你真正的需求是将 json 数据 print 出来时能显示出中文。

你没弄懂的是,Python 在 print 列表和字典等数据结构时,输出的是数据的内部存储格式,也就是说如果里面的元素是中文字符串,Python 不会把中文直接打印出来,而是会把中文的编码打印出来。
例如:
>>> print ['中', '文']
['\xe4\xb8\xad', '\xe6\x96\x87']
相当于每个元素打印的是 repr 的结果:
>>> print repr('中')
'\xe4\xb8\xad'
而如果直接打印其中的元素是能显示中文的:
>>> print ['中', '文'][0]


因此如果你想能显示出中文,不应该直接去 print 整个数据结构 object,应该将其转为相应格式的字符串后再 print。
例如其中一种方法是:
>>> s = repr(['中', '文']).decode('string-escape')
>>> print s
['中', '文']
如果元素是 unicode:
>>> s = repr([u'中', u'文']).decode('unicode-escape')
>>> print s

而如果是 json 数据,更好的方法是用楼上说的方法:
>>> print(json.dumps({u"语言": u"中文"}, ensure_ascii=False))
{"语言": "中文"}
cqcn1991
2015-07-23 08:56:08 +08:00
@Sylv 原来是这样!非常感谢!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/205969

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX