这似乎是世界上最简单的Python的问题......但我想给它解释它的一展身手。

基本上我通过从查询JSON结果的页面具有到环。

标准结果是这样的

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

我需要的循环来继续循环,在结果键可以在以后访问和列表内计数结果的量的无功附加列表。不过我只在时,有没有更多的页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)
有帮助吗?

解决方案

替代(清洁器)的方法,使一个大的列表:

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"])

其他提示

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

该列表被追加作为方法调用的副作用。 append()实际上返回None,所以现在new_resultNone参考。

您想使用

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

如果你坚持做下去的方式。正如巴斯蒂安说,result.append(whatever) == None

AFAICS,你不需要变量new_result都没有。

result_count = len(result)

会给你你需要的答案。

您不能追加到dict..you可以附加到你的列表中选择字典里面,你应该做这样的

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

如果你想检查是否有在结果字典没有下一页价值,你要删除从字典的关键,只是做这样

if not result['next_page']:
    del result['next_page']
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top