Python实现一个简单的天气预报应用程序
发布时间:2023-12-04 21:09:17
天气预报应用程序可以通过调用天气API来获取天气数据,并以用户友好的方式展示给用户。在Python中,可以使用requests库来发送HTTP请求并获取API响应数据,然后使用json库来处理返回的JSON数据。
下面是一个简单的天气预报应用程序的实现,包括通过城市名获取天气的功能和通过经纬度获取天气的功能:
import requests
import json
# 通过城市名获取天气
def get_weather_by_city(city):
api_key = "YOUR_API_KEY"
base_url = "https://api.weatherapi.com/v1/current.json"
params = {
"key": api_key,
"q": city
}
response = requests.get(base_url, params=params)
data = response.json()
if "error" in data:
print("Error:", data['error']['message'])
else:
print("City:", data['location']['name'])
print("Country:", data['location']['country'])
print("Temperature (C):", data['current']['temp_c'])
print("Condition:", data['current']['condition']['text'])
# 通过经纬度获取天气
def get_weather_by_lat_lon(lat, lon):
api_key = "YOUR_API_KEY"
base_url = "https://api.weatherapi.com/v1/current.json"
params = {
"key": api_key,
"q": f"{lat},{lon}"
}
response = requests.get(base_url, params=params)
data = response.json()
if "error" in data:
print("Error:", data['error']['message'])
else:
print("City:", data['location']['name'])
print("Country:", data['location']['country'])
print("Temperature (C):", data['current']['temp_c'])
print("Condition:", data['current']['condition']['text'])
# 通过城市名获取天气的使用例子
city = input("Enter city name: ")
get_weather_by_city(city)
# 通过经纬度获取天气的使用例子
lat = input("Enter latitude: ")
lon = input("Enter longitude: ")
get_weather_by_lat_lon(lat, lon)
注意,上述代码中的YOUR_API_KEY需要替换为你在Weather API网站上注册的API密钥。
上述代码通过requests.get()函数发送GET请求到API的URL中,并将查询参数作为字典传递给params参数。然后,使用返回的API响应创建一个JSON对象,通过访问字典的键来获取所需的天气数据。
实际使用中,可以根据需要对返回的天气数据进行进一步处理和展示,以满足应用程序的需求。
