문제

이것은 세계에서 가장 단순한 파이썬 질문처럼 보일지 모르지만 ... 나는 그것을 설명 할 것입니다.

기본적으로 쿼리의 JSON 결과 페이지를 반복해야합니다.

표준 결과는 이것입니다

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

결과 키의 목록을 var에 추가하고 나중에 액세스 할 수 있고 목록 내의 결과 양을 계산할 수있는 루프가 계속 루프를하려면 루프가 필요합니다. 그러나 더 이상 페이지가 없을 때 다음 _page 키가 Dict에서 삭제됩니다.

현재 나는 이것을 가지고있다

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_result 이제에 대한 참조입니다 None.

당신은 사용하고 싶습니다

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

당신이 그렇게하는 것을 주장한다면. Bastien이 말했듯이 result.append(whatever) == None

Afaics, 당신은 변수 new_result가 필요하지 않습니다.

result_count = len(result)

필요한 답변을 줄 것입니다.

당신은 dict에 추가 할 수 없습니다 .. 당신은 당신의 dict 내에서 당신의 목록에 추가 할 수 있습니다, 당신은 이것을 좋아해야합니다.

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

결과 DICT에 다음 페이지 값이 없는지 확인하고 Dict에서 키를 삭제하려면 이렇게하십시오.

if not result['next_page']:
    del result['next_page']
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top