gpt4 book ai didi

python - 解析 Openweather API Python

转载 作者:太空宇宙 更新时间:2023-11-03 15:26:28 27 4
gpt4 key购买 nike

好吧,我遇到了一些情况,并且在理解如何从 API 返回的 JSON 中提取值方面遇到了障碍。我有以下代码:

import requests
import json

weather_results = []
key = 'somekey'
cities = ['sometown']

def weather_get(apikey, city):
r = requests.get('http://api.openweathermap.org/data/2.5/weather?q={},canada&APPID={}'.format(city, apikey))
return(r.text)

这将返回一长串 JSON 格式,如下所示:

[u'{"coord":{"lon":-73.59,"lat":45.51},"weather":[{"id":521,"main":"Rain","description":"shower rain","icon":"09d"}],"base":"stations","main":{"temp":277.5,"pressure":1022,"humidity":55,"temp_min":277.15,"temp_max":278.15},"visibility":24140,"wind":{"speed":3.1,"deg":300},"clouds":{"all":90},"dt":1490810400,"sys":{"type":1,"id":3829,"message":0.0973,"country":"CA","sunrise":1490783901,"sunset":1490829598},"id":6077243,"name":"Montreal","cod":200}']

现在,如果我写一个像这样的函数:

def get_temp_min(arg):
for items in arg:
data = json.loads(items)
for key, value in data['main'].items():
if key=='temp_min':
return(value)

它将返回以下值,但如果我尝试:

def get_weather_description(arg):
for items in arg:
data = json.loads(items)
for key, value in data['weather'].items():
if key=='description':
return(value)

我没有得到我想要的回复类型。我尝试过类似的方法,看看是否可以更深入地了解 JSON:

def get_weather_description(arg):
for items in arg:
data = json.loads(items)
for key, value in data.items():
if key=='weather':
data2= value
for items in data2:
data3 = items

但我觉得我目前没有走上正确的道路,如果有人可以提供一些建议,我将非常感激。

最佳答案

所以,我做了一些事情来让这变得更好,我已经实现了 @kiran.kodur 的建议

def weather_get(apikey, city):
r = requests.get('http://api.openweathermap.org/data/2.5/weather?q={},canada&APPID={}'.format(city, apikey))
return(r.json())

“return(r.json())”使代码更加清晰:

def get_temp(arg):
for items in arg:
for key, value in items['main'].items():
if key=='temp':
return(value)
def get_pressure(arg):
for items in arg:
for key, value in items['main'].items():
if key=='pressure':
return(value)
def get_temp_min(arg):
for items in arg:
for key, value in items['main'].items():
if key=='temp_min':
return(value)

事实证明我需要修改:

for key, value in data.items()

致:

for key, value in items['weather'][0].items():

我能够通过这个返回我需要的东西。

关于python - 解析 Openweather API Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43101757/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com