问题描述
我在学习教程 https://towardsdatascience.com/getting-weather-data-in-3-easy-steps-8dc10cc5c859 并遇到了一个问题,如果我完全按照他们的方式复制和粘贴代码,它工作正常。但是,如果我更改了站号,则会出错,我将其更改为哪个站都没有关系。
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'
谢谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)