【发布时间】:2021-04-06 06:24:14
【问题描述】:
我在学习一个教程 https://towardsdatascience.com/getting-weather-data-in-3-easy-steps-8dc10cc5c859 遇到了一个问题,如果我完全按照他们的方式复制和粘贴代码,它就可以正常工作。但是,如果我更改了站 ID,则会出现错误,我将其更改为哪个站都没有关系。
import requests
import numpy as np
import pandas as pd
import json
from datetime import datetime
import matplotlib.pyplot as plt
Token = 'YourTokenHere'
station_id = 'GHCND:USW00023129'
station_id1 = 'GHCND:USC00107689'
station_id2 = 'GHCND:USW00003122'
#initialize lists to store data
dates_temp = []
dates_prcp = []
temps = []
#for each year from 2015-2019 ...
for year in range(2015, 2017):
year = str(year)
print('working on year '+year)
#make the api call
r = requests.get('https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCND&datatypeid=TAVG&limit=1000&stationid='
+station_id1+'&startdate='+year+'-01-01&enddate='+year+'-12-31', headers={'token':Token})
#load the api response as a json
d = json.loads(r.text)
#get all items in the response which are average temperature readings
avg_temps = [item for item in d['results'] if item['datatype']=='TAVG']
#get the date field from all average temperature readings
dates_temp += [item['date'] for item in avg_temps]
#get the actual average temperature from all average temperature readings
temps += [item['value'] for item in avg_temps]
如果我使用 station_id GHCND:USW00023129 它工作正常。如果我使用 station_id1 或 2(或任何其他 station_id,我已经尝试了几个),我会收到此错误:
runfile('D:/Code/Weather/Weather.py', wdir='D:/Code/Weather')
working on year 2015
Traceback (most recent call last):
File "D:\Code\Weather\Weather.py", line 36, in <module>
avg_temps = [item for item in d['results'] if item['datatype']=='TAVG']
KeyError: 'results'
谢谢
【问题讨论】:
-
“它坏了”是什么意思?你得到什么错误?
-
另外,请更新您的代码示例,以便我们可以复制/粘贴它并自己尝试。缺少的变量非常清楚,但是如果您在代码中提供
station_id和year的具体示例作为变量,我们将更容易为您提供帮助(并且您将更快地得到答案),以便我们看到一致结果与您看到的相比。 -
我使用的年份似乎并不重要,它总是会在第一个时崩溃。
-
崩溃时的错误信息是什么?请edit你的问题包括它。
-
提示:使用
d = r.json()而不是d = json.loads(r.text)。 IDK 如果这将修复错误,但这是从响应正文中获取 JSON 的正确方法。