【问题标题】:How to find "rain" in a variable for openweathermap如何在openweathermap的变量中找到“雨”
【发布时间】:2021-08-07 22:21:32
【问题描述】:

我正在尝试制作一个简单的程序,它会告诉您今天是否需要给植物浇水(看看今天是否会下雨)。我正在使用 openweathermap api 来做到这一点。 api 不像温度或湿度那样将雨作为变量包含在内,而是仅在下雨作为天气变量的一部分时才显示为“雨”。

当我在下面运行我的代码时,它永远不会知道正在下雨,即使它正在查看的变量包括雨。我想知道如何在变量中找到“rain”一词并相应地打印一条消息。

运行我当前的代码后,如果我打印weathervar,就会得到这样的结果:

[{'id': 502, 'main': 'Rain', 'description': 'heavy intensity rain', 'icon': '10n'}]

即使变量包含“rain”,我的代码也认为它没有。

import requests, json
api_key = "someapikey"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = ("Brunei")
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
    y = x["main"]
    current_temperature = y["temp"]
    weathervar = x["weather"]
else:
    print(" City Not Found ")

if 'Rain' in weathervar:
    print("You don't need to water your plants today.")
else:
    print("You need to water your plants today")
    print(weathervar)

【问题讨论】:

  • 我建议您更改您的帐户信息中的 API 密钥,因为您已经在此处发布了它。这些信息应该是私人的。如果您共享您的 API 密钥,那么知道它的每个人都可以使用您的凭据与 API 进行交互。由于您每次只有一定数量的调用,因此共享此信息不仅不安全,而且其他人可能会自费使用 API。

标签: python openweathermap


【解决方案1】:

由于weathervar是一个字典列表,你应该检查一下

if any(item['main'] == 'Rain' for item in weathervar):

【讨论】:

  • 你打败了我。
  • 对不起,下一个留给你。
  • :-)。善用any()
【解决方案2】:

尝试使用:

import requests, json
api_key = "someapikey"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = ("Brunei")
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
        y = x["main"]
        current_temperature = y["temp"]
        weathervar = x["weather"][0]

else:
    print(" City Not Found ")

if 'Rain' in weathervar.values():
    print("You don't need to water your plants today.")

else:
    print("You need to water your plants today")
    print(weathervar)

首先,您必须将数组转换为正确的字典。然后你可以用.values()询问字典的值。

【讨论】:

  • 您是否提供了您的实际 API 密钥?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-12
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多