使用自然语言处理调用天气 API 的 Python 程序
首先,需要选择一个适合自然语言处理的 Python 库,例如 NLTK 或 Spacy。然后,需要从 API 提供方获取 API 的接口文档和 API 密钥。
下面是一个调用天气 API 的示例程序:
import requests
def get_weather(city):
api_key = 'your_api_key'
url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
weather_description = data['weather'][0]['description']
temperature = data['main']['temp']
humidity = data['main']['humidity']
wind_speed = data['wind']['speed']
print(f'Current weather in {city}: {weather_description}, temperature: {temperature} K, humidity: {humidity} %, wind speed: {wind_speed} m/s')
else:
print('Failed to get weather data')
city = input('Which city's weather do you want to know? ')
get_weather(city)
在这个程序中,我们首先定义了一个函数 get_weather(city),它接受一个城市名作为参数,并使用 API 密钥和城市名构建 API 请求的 URL。然后,我们使用 requests 库发送 GET 请求并获取响应。如果响应状态码为 200,表示请求成功,我们解析响应 JSON 数据并提取天气描述、温度、湿度和风速等信息,并打印出来。如果请求失败,我们将打印出错误信息。
最后,我们通过调用 get_weather(city) 函数并传入用户输入的城市名来获取天气信息。如果用户输入的城市名不正确,API 将返回错误响应。
原文地址: https://www.cveoy.top/t/topic/nF3C 著作权归作者所有。请勿转载和采集!