我是python的新手。我刚刚开始使用openweathermap API进行天气API项目。任何人都可以解释我要去哪里了吗?如何从“天气”中检索“描述”,为什么会引发键盘错误?]
我的从JSON响应中检索“描述”的代码:
import requests
import json from pprint
import pprint
city_name= input("Enter the City name")
complete_url="https://samples.openweathermap.org/data/2.5/weather?q={},uk&appid=b6907d289e10d714a6e88b30761fae22"
+format(city_name)
response=requests.get(complete_url)
data=response.json()
pprint(response.status_code)
temprature=data['main']['temp']
windspeed=data['wind']['speed']
description = data ['weather'] [0] ['description']
print('temprature: {}',format(temprature))
print('windspeed:{}',format(windspeed))
print('Description:{}',format(description))
我的输出是
输入城市名称西雅图200追溯(最近一次通话):在第15行的“ /Users/suprajaraman/PycharmProjects/learnPython/venv/weather.py”文件中description = data ['weather'] [0] [description] NameError:未定义名称'description'
JSON响应
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 300,
"main": "Drizzle",
"description": "light intensity drizzle",
"icon": "09d"
}
],
"base": "stations",
"main": {
"temp": 280.32,
"pressure": 1012,
"humidity": 81,
"temp_min": 279.15,
"temp_max": 281.15
},
"visibility": 10000,
"wind": {
"speed": 4.1,
"deg": 80
},
"clouds": {
"all": 90
},
"dt": 1485789600,
"sys": {
"type": 1,
"id": 5091,
"message": 0.0103,
"country": "GB",
"sunrise": 1485762037,
"sunset": 1485794875
},
"id": 2643743,
"name": "London",
"cod": 200
}
问题是windspeed=data['wind'][0]['speed']
,您要Python在其中访问wind
列表的第0个索引,实际上它不存在(wind
是字典)。
import json
content = """{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 300,
"main": "Drizzle",
"description": "light intensity drizzle",
"icon": "09d"
}
],
"base": "stations",
"main": {
"temp": 280.32,
"pressure": 1012,
"humidity": 81,
"temp_min": 279.15,
"temp_max": 281.15
},
"visibility": 10000,
"wind": {
"speed": 4.1,
"deg": 80
},
"clouds": {
"all": 90
},
"dt": 1485789600,
"sys": {
"type": 1,
"id": 5091,
"message": 0.0103,
"country": "GB",
"sunrise": 1485762037,
"sunset": 1485794875
},
"id": 2643743,
"name": "London",
"cod": 200
}"""
data = json.loads(content)
print(f'Temp is {data["main"]["temp"]}, and wind speed is {data["wind"]["speed"]}.')
输出:
Temp is 280.32, and wind speed is 4.1.