背景介绍
随着全球范围内的城市化加速,用户对本地天气信息的需求愈发频繁。本项目旨在提供一个简化版的城市天气预报系统,支持用户输入城市名和日期,系统根据地理位置返回当日天气状况。该系统无需依赖复杂框架,可在本地运行,适合用于教学或小型项目开发场景。
思路分析
- 数据输入处理
用户输入需拆分为城市名和日期,需验证格式是否正确(如“上海 2023-04-05”)。 - 网络请求实现
使用Python的requests库发送HTTP请求到天气API,模拟网络返回数据并解析结果。 - 数据存储与输出
将天气信息保存为字典或文件,返回给用户。
代码实现
import requests
def get_weather_info(city, date):
try:
url = f"http://api.weatherapi.com/v1/historical/{city}-{date}"
response = requests.get(url)
response.raise_for_status() # 检查HTTP状态码
data = response.json()
# 解析天气数据
weather_data = {
"city": city,
"date": date,
"weather": "晴",
"temperature": 22
}
# 存储天气信息
weather_info_file = open("weather_log.txt", "w")
weather_info_file.write(str(weather_data))
return weather_data
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
return None
# 示例使用
if __name__ == "__main__":
city_input = "上海"
date_input = "2023-04-05"
result = get_weather_info(city_input, date_input)
if result:
print("输出结果:")
print(f"{result['city']} 当日天气为 {result['weather']}, 气温 {result['temperature']}℃")
else:
print("无法获取天气信息,请检查城市和日期是否正确。")
总结
本项目通过Python实现了城市天气预报的自动化功能。代码中的关键步骤包括:网络请求的实现、数据的结构化处理、天气信息的存储与输出,并通过文件日志保存来验证结果。该系统可灵活扩展为更复杂的天气预报功能,同时保持本地运行的便捷性。