[英]I am trying to parse information from a JSON URL file using two user inputs from python
這是通過詢問用戶輸入而成功運行的代碼,在本例中為 state
import requests
import simplejson as json
response = requests.get("https://api.covidtracking.com/v1/states/ca/daily.json")
json_test = response.json()
print("Enter the state for which the COVID data should be retrieved (e.g. TX): ")
user_state = input()
count = 0
for i in json_test:
i = count
count = count + 1
state = (json_test[i]['state'])
dates = (json_test[i]['date'])
if state == user_state:
death = (json_test[i]['death'])
print("State: " + str(state))
print("Date: " + str(dates))
print("Death(s)" + str(death))
print("===============")
output 將類似於:
Date: 20201112
Death(s)18108
===============
State: CA
Date: 20201111
Death(s)18070
===============
State: CA
Date: 20201110
Death(s)18001
===============
State: CA
Date: 20201109
Death(s)17977
===============
但我正在嘗試實現用戶在命令行上輸入 US state 和日期的選項,如下所示:
Enter the state for which the COVID data should be retrieved (e.g. TX): CA
Enter the date for which the COVID data should be retrieved (e.g. 20201219): 20210219
我試過的代碼是:
import requests
import simplejson as json
response = requests.get("https://api.covidtracking.com/v1/states/ca/daily.json")
json_test = response.json()
print("Enter the state for which the COVID data should be retrieved (e.g. TX): ")
user_state = input()
print("Enter the date for which the COVID data should be retrieved (e.g. 20201219): ")
user_date = input()
count = 0
for i in json_test:
i = count
count = count + 1
state = (json_test[i]['state'])
dates = (json_test[i]['date'])
if state == user_state and dates == user_date:
death = (json_test[i]['death'])
print("State: " + str(state))
print("Date: " + str(dates))
print("Death(s)" + str(death))
print("===============")
但是,我的 output 沒有結果,但也沒有錯誤。 我現在知道為什么它不起作用
這里從 url 收到的日期值具有int
數據類型,您需要將其轉換為string
以進行比較。 此代碼將完美運行:
import requests
import simplejson as json
response = requests.get("https://api.covidtracking.com/v1/states/ca/daily.json")
json_test = response.json()
user_state = input("Enter the state for which the COVID data should be retrieved (e.g. TX): ")
user_date = input("Enter the date for which the COVID data should be retrieved (e.g. 20201219): ")
count = 0
for i in json_test:
i = count
count = count + 1
state = (json_test[i]['state'])
dates = (json_test[i]['date'])
if((state == user_state)and(str(dates) == user_date)):
death = (json_test[i]['death'])
print("State: " + str(state))
print("Date: " + str(dates))
print("Death(s): " + str(death))
print("===============")
輸入
Enter the state for which the COVID data should be retrieved (e.g. TX): CA
Enter the date for which the COVID data should be retrieved (e.g. 20201219): 20210305
Output
State: CA
Date: 20210305
Death(s): 53448
===============
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.