Wunderground API获取每小时的预测返回错误. - Python [英] Wunderground API to get hourly forecast returns error. - Python
问题描述
我正在尝试从Wunderground API获取每小时的预测,但是我的代码返回了此错误.
I'm trying to get the hourly forecast from the Wunderground API but my code returns this error.
回溯(最近通话最近): 在第10行中输入"weathergraph.py"文件 预报= parsed_json ['hourly_forecast'] ['FCTTIME'] ['temp'] ['english'] TypeError:列表索引必须是整数,而不是str
Traceback (most recent call last): File "weathergraph.py", line 10, in forecast = parsed_json['hourly_forecast']['FCTTIME']['temp']['english'] TypeError: list indices must be integers, not str
这是我的代码.
f = urllib2.urlopen('http://api.wunderground.com/api/mykey/hourly/q/NY/New_York_City.json')
f=urllib2.urlopen('http://api.wunderground.com/api/mykey/hourly/q/NY/New_York_City.json')
json_string = f.read()
json_string = f.read()
parsed_json = json.loads(json_string)
parsed_json = json.loads(json_string)
forecast = parsed_json ['hourly_forecast'] ['FCTTIME'] ['temp'] ['english']
forecast = parsed_json['hourly_forecast']['FCTTIME']['temp']['english']
f.close()
parsed_json = http://pastie.org/3905346
parsed_json = http://pastie.org/3905346
推荐答案
1)hourly_forecast的值是字典列表,而不是字典.看起来像列表中的36.
1) The value of hourly_forecast is a list of dicts, not a dict. Looks like about 36 in the list.
2)temp不是FCTTIME的元素.它们处于同一级别
2) temp is not an element of FCTTIME. They are at the same level
这不应产生错误:
forecast = parsed_json['hourly_forecast'][-1]['temp']['english']
列表似乎按时间顺序排列,所以最后一个是最新的.检查FCTTIME的内容将告诉您它与您上次阅读的内容是否不同.
It looks like the list is in order by time, so the last one is most recent. Checking the contents of FCTTIME will tell you whether it is different from the last time that you read it.
这篇关于Wunderground API获取每小时的预测返回错误. - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!