使用pyowm获得平均tempature(python)

问题描述 投票:1回答:3

我想在我的python代码中显示平均温度。

我发现http://openweathermap.org/,他们的API我做了以下代码:

import pyowm

api = pyowm.OWM('Your API key')
collectinfo = api.weather_at_place("Gorinchem,nl")
short = collectinfo.get_weather()
temperature = short.get_temperature('celsius')
print(temperature)

然而温度函数显示多个变量,例如

temp':18.72,'temp_max':20.0,'temp_min':17.0,'temp_kf':无

我想将平均温度写入变量,以便我可以在我的程序中使用它。

经过一番搜索,我找到了以下代码行:

average_temperature(unit='kelvin') 

部分

class pyowm.webapi25.historian.Historian(station_history)

链接到文档:https://pyowm.readthedocs.io/en/latest/pyowm.webapi25.html#module-pyowm.webapi25.observation

(使用ctrl + f,搜索摄氏度,它是第一个弹出)

我不知道如何将该功能用于平均温度。

谁可以帮助一个起始编码器:)?

python python-3.x pip weather-api
3个回答
1
投票

好吧,我最近遇到了同样的问题,如果不使用你不知道如何使用的功能,就更容易知道如何从初始结果中获取你想要的数据!

 observation = self.owm.weather_at_place("Gorinchem,nl")
 w = observation.get_weather()
 temperature = w.get_temperature('celsius')

这将在这个时刻输出我们:{'temp': 8.52, 'temp_max': 10.0, 'temp_min': 7.22, 'temp_kf': None}

但我们需要了解这是什么样的结果:

print(type(temperature))

这将输出我们的结果类型:

<class 'dict'>

有了这个,我们现在知道,如果我们访问密钥,我们可以单独访问这些值:

avgTemp=temperature['temp']

这是因为平均温度(qazxsw poi)的关键是qazxsw poi。

为了确保您可以使用它,我们需要知道它是什么类型:

8.52

哪个会输出:

'temp'

1
投票

字符串的格式适合初始化python dict。

print(type(tempMedia))

请注意,我在字符串的开头添加了一个缺少的<class 'float'> 。请注意,使用s = "'temp': 18.72, 'temp_max': 20.0, 'temp_min': 17.0, 'temp_kf': None" data = eval('{{{}}}'.format(s)) print data['temp'] 通常被认为是一种安全风险,因为该字符串可能包含恶意的python代码,可能在调用eval时执行。

另一种方法是使用正则表达式来改进字符串的解析,例如,您可以过滤所有小数值,并依赖于您要查找的值始终位于某个位置的事实:

'

0
投票

我以一种不可靠的方式解决了这个问题。我将输出转换为字符串。然后我就拉出了我需要的角色。最后我将它们组合在一起。这是一种丑陋的方式,但至少我可以继续。如果有人知道更好的解决方案继续!

eval
© www.soinside.com 2019 - 2024. All rights reserved.