如何处理编码?

时间:2013-11-13 05:01:47

标签: python json

import json
import urllib2
url = "http://api.douban.com/v2/book/1220562"
hdr = { 'User-Agent' : 'super happy flair bot by /u/spladug' }
req = urllib2.Request(url, headers=hdr)
html = urllib2.urlopen(req).read()
html = json.loads(html)
func_name = 'callback'
html = '{0}({1})'.format(func_name, html)
print html

输出:

callback({u'rating': {u'max': 10, u'numRaters': 310, u'average': u'7.0', u'min': 0}, u'subtitle': u'', u'pubdate': u'2005-1', u'image': u'http://img3.douban.com/mpic/s1747553.jpg', u'binding': u'\u5e73\u88c5',..............})

我希望输出编码为gb2312或更好的东西。可能就像

callback({'rating': {'max': 10, 'numRaters': 310, 'average': '7.0', 'min': 0......})

示例输出:url

2 个答案:

答案 0 :(得分:1)

你的问题不在于编码,至少还没有。

您正在使用'{0}({1})'.format(func_name, html)将字典转换为字符串。

您应该使用json.dumps将python对象转换为json字符串。

json.dumps有一个参数ensure_ascii,其默认值为True。它使用\ uXXXX序列转义输出中的所有非ASCII字符,结果是仅包含ASCII字符的str实例。如果ensure_ascii为False,则结果可能包含非ASCII字符,返回值可能是unicode实例。

json.dumps(html, ensure_ascii=False)

答案 1 :(得分:1)

考虑切换到Python 3,它将显示非ASCII字符而不是Unicode代码点。我通过Python安装的2to3.py目录中提供的Tools\Scripts转换器运行代码,然后添加了UTF-8解码和漂亮的打印:

import json
import urllib.request, urllib.error, urllib.parse
import pprint
url = "http://api.douban.com/v2/book/1220562"
hdr = { 'User-Agent' : 'super happy flair bot by /u/spladug' }
req = urllib.request.Request(url, headers=hdr)
html = urllib.request.urlopen(req).read().decode('utf8')
html = json.loads(html)
pprint.pprint(html)

在支持中文的合适终端或IDE上输出:

{'alt': 'http://book.douban.com/subject/1220562/',
 'alt_title': '',
 'author': ['[日] 片山恭一'],
 'author_intro': '',
 'binding': '平装',
 'catalog': '\n      ',
 'id': '1220562',
 'image': 'http://img3.douban.com/mpic/s1747553.jpg',
 'images': {'large': 'http://img3.douban.com/lpic/s1747553.jpg',
            'medium': 'http://img3.douban.com/mpic/s1747553.jpg',
            'small': 'http://img3.douban.com/spic/s1747553.jpg'},
 'isbn10': '7543632608',
 'isbn13': '9787543632608',
 'origin_title': '',
 'pages': '180',
 'price': '15.00元',
 'pubdate': '2005-1',
 'publisher': '青岛出版社',
 'rating': {'average': '7.0', 'max': 10, 'min': 0, 'numRaters': 310},
 'subtitle': '',
 'summary': '那一年,是听莫扎特、钓鲈鱼和家庭破裂的一年。说到家庭破裂,母亲怪自己当初没有找到好男人,父亲则认为当时是被狐狸精迷住了眼,失常的是母亲,但出问题的是父亲……。',
 'tags': [{'count': 120, 'name': '片山恭一', 'title': '片山恭一'},
          {'count': 57, 'name': '日本', 'title': '日本'},
          {'count': 50, 'name': '日本文学', 'title': '日本文学'},
          {'count': 33, 'name': '小说', 'title': '小说'},
          {'count': 31, 'name': '满月之夜白鲸现', 'title': '满月之夜白鲸现'},
          {'count': 11, 'name': '爱情', 'title': '爱情'},
          {'count': 8, 'name': '外国文学', 'title': '外国文学'},
          {'count': 7, 'name': '純愛', 'title': '純愛'}],
 'title': '满月之夜白鲸现',
 'translator': ['豫人'],
 'url': 'http://api.douban.com/v2/book/1220562'}