2017-06-01 63 views
0

我想显示我的python代码中的平均温度。使用pyowm获取平均tempature(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) 

尚tempature功能例如显示多个变量

温度“:18.72, 'temp_max':20.0, 'temp_min':17.0, 'temp_kf':无

我想刚刚已经平均tempture写入到一个变量,这样我可以在我的程序中使用它。

经过一番搜索,我发现下面的代码行:

部分
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键,搜索摄氏度它是第一个弹出)

我不知道如何使用功能为平均温度。

任何人谁可以帮助开始编码器:)?

回答

1

该字符串的格式适合于初始化python字典。

s = "'temp': 18.72, 'temp_max': 20.0, 'temp_min': 17.0, 'temp_kf': None" 
data = eval('{{{}}}'.format(s)) 
print data['temp'] 

请注意,我在字符串的开头添加了缺少的'。 被警告使用eval通常被认为是一种安全风险,因为该字符串可能包含在调用eval时可能会执行的恶意python代码。

另一种方法是使用正则表达式来改善对字符串的解析,例如,你可以过滤所有的十进制值,并依赖于一个事实,即你正在寻找的值总是在某个位置:

import re 
s = "'temp': 18.72, 'temp_max': 20.0, 'temp_min': 17.0, 'temp_kf': None" 
temperatures = [float(q) for q in re.findall(r'([\d\.]+)', s)] 
+0

我知道我在用的API,并且我不认为这将是恶意的。所以eval的安全风险是不对的? –

+0

@AntonvanderWel我想是的,是的。 –

0

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

s = "temp': 18.72, 'temp_max': 20.0, 'temp_min': 17.0, 'temp_kf': None" 


h1 =s[7] 
h2 =s[8] 
k1=s[10] 
print(h1+h2+","+k1)