0

这似乎是世界上最简单的 python 问题......但我将尝试解释一下。

基本上我必须遍历查询的 json 结果页面。

标准结果是这样的

{'result': [{result 1}, {result 2}], 'next_page': '2'}

我需要循环继续循环,将结果键中的列表附加到一个 var 中,以后可以访问并计算列表中的结果数量。但是,我要求它仅在 next_page 存在时循环,因为过了一会儿,当没有更多页面时,next_page 键将从字典中删除。

目前我有这个

next_page = True
while next_page == True:
    try:
        next_page_result = get_results['next_page'] # this gets the next page
        next_url = urllib2.urlopen("http://search.twitter.com/search.json" + next_page_result)# this opens the next page
        json_loop = simplejson.load(next_url) # this puts the results into json
        new_result = result.append(json_loop['results']) # this grabs the result and "should" put it into the list
    except KeyError:
        next_page = False   
        result_count = len(new_result)
4

5 回答 5

4

替代(更清洁)方法,列出一个大清单:

results = []
res = { "next_page": "magic_token_to_get_first_page" }
while "next_page" in res:
    fp = urllib2.urlopen("http://search.twitter.com/search.json" + res["next_page"])
    res = simplejson.load(fp)
    fp.close()
    results.extend(res["results"])
于 2009-11-01T01:24:15.327 回答
2
new_result = result.append(json_loop['results'])

该列表作为方法调用的副作用附加。 append()实际上返回None,所以new_result现在是对None.

于 2009-11-01T01:04:25.427 回答
1

你想用

result.append(json_loop['results']) # this grabs the result and "should" put it into the list
new_result = result

如果你坚持这样做。正如巴斯蒂安所说,result.append(whatever) == None

于 2009-11-01T01:17:14.730 回答
0

AFAICS,您根本不需要变量 new_result。

result_count = len(result)

会给你你需要的答案。

于 2009-11-01T01:18:41.357 回答
0

你不能追加到字典中。你可以追加到字典中的列表中,你应该这样做

result['result'].append(json_loop['results'])

如果你想检查结果字典中是否没有下一页值,并且你想从字典中删除键,就这样做

if not result['next_page']:
    del result['next_page']
于 2009-11-01T03:50:06.887 回答