我有一个python脚本,它向API发出一个http请求,以便提取“成员”数据。然后它运行一个循环来命中几个不同的成员ID(在文本文件中列出),看看它们是否都“过期”。我想要做的是打印出这些结果的摘要,而不是打印出每个成员的单独结果。这是我的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"
如果返回的状态为“true”,找出特定成员的ID也会有所帮助:
"Member 1234 returned True"
或类似的东西。任何帮助是极大的赞赏。
谢谢!
答案 0 :(得分: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),上面的代码是正确的。
答案 1 :(得分: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
答案 2 :(得分:0)
您可以在for循环外使用两个计数器,然后根据True
或False
增加计数器,如下所示:
# 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)))
这将导致两次检查的总和。