0
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

4

2 に答える 2

1

あなたの問題は、少なくとも、まだエンコードに関するものではありません。

を使用して辞書を文字列に変換しています'{0}({1})'.format(func_name, html)

Python オブジェクトを json 文字列に変換するには、json.dumps を使用する必要があります。

json.dumpsには、デフォルト値が True であるパラメーターensure_asciiがあります。出力内のすべての非 ASCII 文字を \uXXXX シーケンスでエスケープし、結果は ASCII 文字のみで構成される str インスタンスになります。ensure_ascii が False の場合、結果には非 ASCII 文字が含まれる可能性があり、戻り値は Unicode インスタンスである可能性があります。

json.dumps(html, ensure_ascii=False)
于 2013-11-13T05:20:33.480 に答える
1

Unicode コードポイントの代わりに非 ASCII 文字を表示する Python 3 に切り替えることを検討してください。2to3.pyPython のインストールディレクトリにあるコンバーターを使用してコードを実行し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'}
于 2013-11-13T06:53:11.940 に答える