【问题标题】:using pyowm getting the average tempature (python)使用 pyowm 获取平均温度(python)
【发布时间】:2017-11-02 07:46:30
【问题描述】:

我想在我的 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 函数显示多个变量,例如

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 ,搜索 celsius 最先弹出)

我不知道如何使用该函数来计算平均温度。

任何可以帮助初学者的人:)?

【问题讨论】:

    标签: python python-3.x pip weather-api


    【解决方案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']
    

    这是因为平均温度 (8.52) 的键是 'temp'

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

    print(type(tempMedia))
    

    将输出:

    <class 'float'>
    

    【讨论】:

      【解决方案2】:

      字符串的格式适合初始化 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)]
      

      【讨论】:

      • 我知道我使用的是什么 API,我认为它不会是恶意的。所以eval的安全风险是不对的?
      • @AntonvanderWel 我想是的,是的。
      【解决方案3】:

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

      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)
      

      【讨论】:

      • 检查我刚刚写的内容!
      猜你喜欢
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      相关资源
      最近更新 更多