2017-06-01 62 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)