2017-04-01 194 views
1

我有一個python腳本,它向一個API發出一個http請求來拉取「成員」數據。然後它運行一個循環來打幾個不同的成員ID(在一個文本文件中列出),看他們每個人是否「過期」。我想要做的是打印出這些結果的摘要,而不是打印出每個成員的單獨結果。這裏是我的Python腳本:在Python中打印結果彙總

import requests 
import json 

qa_members = open("numbers_members.txt") 
arraylist = [] 
    for line in qa_members.readlines(): 
    arraylist.extend(line.split()) 
qa_members.close() 

arraylist = map(int, arraylist) 


authorization_code = raw_input("please enter your authorization code: ") 
members = arraylist 
print "Member Check Starting" 

for member in members: 
    url = "http://api22.wiki.com/v1.12/member?id="+str(member) 

    header = {"Authorization": authorization_code} 

    response = requests.get(url, headers=header) 

    member_check = json.loads(response.text) 

    final_member_status = member_check["response"]["member"] 
    ["is_expired"] 

    print str(member) + " expired status: " + str(final_member_status) 


if final_member_status == False: 
    print "All Members Passed" 
else: 
    print "Some members are expired, please refer to log" 

print "Member Check Complete" 

由此看來,我得到幾個端子輸出,如:

123 expired status: False 
567 expired status: False 

有沒有辦法替代,打印出結果的總結?這可能是這樣的:

"24 members returned False" 
"11 members returned True" 

這也將有助於找出一個特定成員的ID,如果返回的狀態是「真」:

"Member 1234 returned True" 

或者類似的東西。任何幫助是極大的讚賞。

謝謝!

回答

0

第一個念頭:

falsecount = 0 
truecount = 0 
for member in members: 
    url = "http://api22.wiki.com/v1.12/member?id="+str(member) 

    header = {"Authorization": authorization_code} 

    response = requests.get(url, headers=header) 

    member_check = json.loads(response.text) 

    final_member_status = member_check["response"]["member"]["is_expired"] 

    if final_member_status = False: 
     falsecount += 1 
    else: 
     truecount +=1 

print str(falsecount) + "members returned False" 
print str(truecount) + "members returned False" 

編輯

我不能不過的final_member_status = member_check["response"]["member"]["is_expired"]輸出是什麼檢查。這可能是"False"False(因此,字符串或實際評估),如果它是"False"(字符串),那麼我的行應讀if final_member_status = "False",但是,如果它是評估(如果提到的子字段不存在返回False )上面的代碼是正確的。

+0

謝謝!這工作:) – user7681184

0

創建列表和追加的結果是:

results = [] 

for member in members: 
    (...) 
    results.append(str(final_member_status)) 

How can I count the occurrences of a list item in Python?

>>> [1, 2, 3, 4, 1, 4, 1].count(1) 
3 
+0

這個選項是比較慢,然後創建一個int值,並簡單地在每一輪計數'+ 1'。但是,如果您希望能夠回溯輸出,這確實是一個更好的選擇。 – Montmons

0

您可以使用兩個計數器以外的循環,然後增加基於TrueFalse,一些櫃檯像這樣:

# Set both counts to 0 outside the for loop 
true_count = 0 
false_count = 0 

# increment count values based on check inside the for loop 
if final_member_status : 
    true_count = true_count + 1 
else : 
    false_count = false_count + 1 

# And finally print outside for loop in the desired format 
print("{} members returned True".format(str(true_count))) 
print("{} members returned False".format(str(false_count))) 

這將導致兩次檢查的總和。