欢迎访问宙启技术站
智能推送

使用Python编写一个简单的天气预报应用

发布时间:2023-12-04 08:20:03

在Python中编写一个简单的天气预报应用,我们可以使用第三方库pyowm来获取天气数据。下面是一个示例代码:

import pyowm

# Enter your API key from OpenWeatherMap here
API_KEY = 'your-api-key'

# Create an instance of the OpenWeatherMap client
owm = pyowm.OWM(API_KEY)

def get_weather(city):
    try:
        # Search for the given city
        observation = owm.weather_at_place(city)
        w = observation.get_weather()

        # Get the temperature, humidity and status
        temperature = w.get_temperature('celsius')['temp']
        humidity = w.get_humidity()
        status = w.get_status()

        # Print the weather information
        print(f"Weather in {city}:")
        print(f"Temperature: {temperature}°C")
        print(f"Humidity: {humidity}%")
        print(f"Status: {status}")

    except pyowm.exceptions.api_response_error.NotFoundError:
        print(f"City '{city}' not found")

# Example usage
get_weather('London')

在代码中,首先我们需要在OpenWeatherMap网站上注册一个账号,获取一个API key。替换代码中的API_KEY变量为你自己的API key。

然后,我们通过pyowm.OWM创建了一个OpenWeatherMap客户端的实例,并使用owm.weather_at_place来搜索给定城市的天气数据。我们使用get_temperature获取温度,get_humidity获取湿度,get_status获取天气状态。最后,我们打印了天气信息。

在示例中,我们调用了get_weather('London')函数来获取伦敦的天气信息。你可以替换get_weather函数的参数为你想查询的城市名称。

运行示例代码后,你将会看到类似以下的输出:

Weather in London:
Temperature: 12.2°C
Humidity: 70%
Status: Clouds

这个简单的天气预报应用使用了pyowm库,可以方便地获取天气数据。你可以根据自己的需求扩展这个应用,比如添加更多的天气信息、设计用户交互界面等。