欢迎光临
我们一直在努力

python wether

import requests


def get_city_code(api_key, city_name):
"""
通过高德地图地理编码API将城市名转换为城市编码(adcode)
"""
base_url = "https://restapi.amap.com/v3/geocode/geo"

params = {
"key": api_key,
"address": city_name,
"output": "JSON"
}

try:
response = requests.get(base_url, params=params, timeout=10)

if response.status_code == 200:
result = response.json()

if result.get("status") == "1" and int(result.get("count", 0)) > 0:
# 提取第一个匹配结果的adcode
geocodes = result.get("geocodes", [])
if geocodes:
return geocodes[0].get("adcode")
print(f"无法找到城市'{city_name}'的编码,错误信息:{result.get('info')}")
return None
else:
print(f"地理编码请求失败,HTTP状态码:{response.status_code}")
return None

except Exception as e:
print(f"地理编码请求发生异常:{str(e)}")
return None


def get_weather(api_key, city_code, extensions='base', output='JSON'):
"""
调用高德地图天气查询API获取天气信息
"""
base_url = "https://restapi.amap.com/v3/weather/weatherInfo"

params = {
"key": api_key,
"city": city_code,
"extensions": extensions,
"output": output
}

try:
response = requests.get(base_url, params=params, timeout=10)

if response.status_code == 200:
result = response.json()

if result.get("status") == "1":
print(f"请求成功,信息:{result.get('info')}")
return result
else:
print(f"接口返回错误:{result.get('info')},错误码:{result.get('infocode')}")
return None
else:
print(f"请求失败,HTTP状态码:{response.status_code}")
return None

except Exception as e:
print(f"请求发生异常:{str(e)}")
return None


def get_clothing_suggestion(temperature):
"""根据温度给出穿衣建议"""
try:
temp = float(temperature)
if temp < -15:
return "8级,很冷,建议穿棉衣、羽绒服、冬大衣、皮夹克加羊毛衫、厚呢外套、呢帽、手套等;年老体弱者尽量少外出。"
elif -15 <= temp < 5:
return "7级,冷,建议穿棉衣、羽绒服、冬大衣、皮夹克、毛衣再外罩大衣等;年老体弱者应注意保暖防冻。"
elif 5 <= temp < 15:
return "6级,凉,适宜着一到两件羊毛衫、大衣、毛套装、皮夹克等春秋着装;年老体弱者宜着大衣、夹衣或风衣加羊毛衫等厚型春秋着装。"
elif 15 <= temp < 20:
return "5级,凉爽、较舒适,适宜着夹衣、马甲衬衫、长袖衫、T恤衫、西服套装加薄羊毛衫等春秋着装;年老体弱者:宜着单层棉麻面料的短套装。"
elif 20 <= temp < 25:
return "4级,舒适、最可接受,天气暖和,适宜着单衣或加麻布短衫、T恤衫、薄牛仔衫裤、休闲服、职业套装等春秋过渡装。"
elif 25 <= temp < 28:
return "3级,热、较舒适,天气偏热,适宜着短衫、短裙、短套装、T恤等夏季服装;年老体弱者:单层薄衫裤、薄型棉衫。"
elif 28 <= temp < 33:
return "2级,热、不舒适,天气炎热,适宜着短衫、短裙、短裤、薄型T恤衫、敞领短袖棉衫等夏季服装。"
else: # temp >= 33
return "1级,极热、极不舒适,天气极热,适宜着丝麻、轻棉织物制作的短衣、短裙、薄短裙、短裤等夏季服装。"
except ValueError:
return "无法获取温度,无法提供穿衣建议"


def print_weather_info(weather_data):
"""打印天气信息及穿衣建议"""
if not weather_data:
print("没有可显示的天气数据")
return

# 打印基本信息
print(f"\n数据发布时间: {weather_data.get('lives', [{}])[0].get('reporttime', '未知')}")
print(f"城市: {weather_data.get('lives', [{}])[0].get('city', '未知')}")
print(f"省份: {weather_data.get('lives', [{}])[0].get('province', '未知')}")

# 如果是实况天气
if 'lives' in weather_data and weather_data['lives']:
live = weather_data['lives'][0]
print("\n=== 实况天气 ===")
print(f"天气现象: {live.get('weather', '未知')}")
temperature = live.get('temperature', '未知')
print(f"实时气温: {temperature}℃")
print(f"风向: {live.get('winddirection', '未知')}")
print(f"风力: {live.get('windpower', '未知')}级")
print(f"湿度: {live.get('humidity', '未知')}%")
clothing_suggestion = get_clothing_suggestion(temperature)
print(f"\n穿衣建议: {clothing_suggestion}")

# 如果是预报天气
if 'forecasts' in weather_data and weather_data['forecasts']:
forecast = weather_data['forecasts'][0]
print("\n=== 预报天气 ===")
print(f"预报发布时间: {forecast.get('reporttime', '未知')}")

for cast in forecast.get('casts', []):
print(f"\n日期: {cast.get('date', '未知')} (星期{cast.get('week', '未知')})")
print(f"白天天气: {cast.get('dayweather', '未知')}")
print(f"夜间天气: {cast.get('nightweather', '未知')}")
day_temp = cast.get('daytemp', '未知')
night_temp = cast.get('nighttemp', '未知')
print(f"温度范围: {night_temp}℃ ~ {day_temp}℃")
print(f"白天风向: {cast.get('daywind', '未知')}")
print(f"夜间风向: {cast.get('nightwind', '未知')}")
print(f"白天风力: {cast.get('daypower', '未知')}级")
print(f"夜间风力: {cast.get('nightpower', '未知')}级")
# 取白天温度做穿衣建议
clothing_suggestion = get_clothing_suggestion(day_temp)
print(f"\n穿衣建议: {clothing_suggestion}")


if __name__ == "__main__":
# 配置参数
API_KEY = "6502a6734d301e7f0a53ce7e8801bb81" # 替换为你申请的高德地图API Key

# 获取用户输入的城市名
city_name = input("请输入要查询天气的城市或地区名:")

# 将城市名转换为城市编码
print(f"正在查询'{city_name}'的天气信息...")
city_code = get_city_code(API_KEY, city_name)

if not city_code:
print("无法获取城市编码,程序退出")
else:
print(f"获取到城市编码: {city_code}")

# 获取实况天气
print("\n===== 查询实况天气 =====")
live_weather = get_weather(API_KEY, city_code, extensions='base')
print_weather_info(live_weather)

# 获取预报天气
print("\n\n===== 查询预报天气 =====")
forecast_weather = get_weather(API_KEY, city_code, extensions='all')
print_weather_info(forecast_weather)
赞(0) 打赏
未经允许不得转载:留留工作室 » python wether

评论 抢沙发

更好的WordPress主题

支持快讯、专题、百度收录推送、人机验证、多级分类筛选器,适用于垂直站点、科技博客、个人站,扁平化设计、简洁白色、超多功能配置、会员中心、直达链接、文章图片弹窗、自动缩略图等...

联系我们联系我们

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册