سؤال

قد يبدو هذا مثل العالم أبسط سؤال ثعبان ... لكنني سأعطيه موضحا لشرحه.

أساسا لا بد لي من حلقة من خلال صفحات JSON النتائج من استفسار.

النتيجة القياسية هي هذا

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

أحتاج إلى حلقة لمواصلة حلقة، إلحاق القائمة بإلغاء القائمة في مفتاح النتيجة إلى VAR يمكن الوصول إليها لاحقا واحسب مقدار النتائج داخل القائمة. ومع ذلك، فأنا بحاجة إلى حلقة فقط أثناء next_page موجود كما بعد فترة من الوقت عندما لا تكون هناك صفحات أخرى يتم إسقاط مفتاح Next_Page من DCT.

حاليا لدي هذا

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

إذا كنت تصر على القيام بذلك بهذه الطريقة. كما قال باسيان، result.append(whatever) == None

AFAICS، لا تحتاج إلى NEW_RESULT المتغير على الإطلاق.

result_count = len(result)

سوف أعطيك الجواب الذي تحتاجه.

لا يمكنك إلحاق الدقة في DICT .. يمكنك إلحاق بقائمتك داخل DCT الخاص بك، يجب عليك القيام بذلك

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

إذا كنت ترغب في التحقق مما إذا كانت هناك قيمة صفحة التالية في النتيجة الخاصة بك، وتريد حذف المفتاح من DCT، فما عليك سوى القيام بذلك

if not result['next_page']:
    del result['next_page']
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top