使用chatGPT编写Python脚本以获取周围温度!

我想做一些Python项目,而我足够懒,使用ChatGPT来做一些项目!有趣的是,我没有使用ChatGPT来编写这个故事,但我正在使用ChatGPT来给我获取我的位置的温度的Python代码。

首先,我让chatGPT为我编写一个Python代码,以提供周围温度读数。它立即生成了使用天气服务API、使用温度传感器获取信息和获取系统温度的代码。由于我没有温度传感器,因此选择使用API。以下是代码:

import requests

# Replace 'YOUR_API_KEY' with your actual API key
api_key = 'YOUR_API_KEY'
# Replace 'CITY_NAME' with the name of the city you want the temperature for
city_name = 'CITY_NAME'

# Make a request to OpenWeatherMap API
response = requests.get(f'http://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={api_key}')

if response.status_code == 200:
data = response.json()
temperature = data['main']['temp']
print(f"The temperature in {city_name} is {temperature} degrees Celsius.")
else:
print("Error occurred while fetching temperature.")

正如上面的代码所示,该脚本使用openweathermap。然而我发现它是基于订阅的,所以我搜索了一下能够在我的位置提供天气数据的免费API。我了解了weatherstack,然后我请求chatGPT给我提供一个使用weatherstack API服务的python脚本。以下是chatGPT提供的代码:

import requests

# Replace 'YOUR_API_KEY' with your actual Weatherstack API key
api_key = 'YOUR_API_KEY'
# Replace 'YOUR_LOCATION' with the desired location
location = 'YOUR_LOCATION'

# Make a request to the Weatherstack API
response = requests.get(f'http://api.weatherstack.com/current?access_key={api_key}&query={location}')

if response.status_code == 200:
data = response.json()
temperature = data['current']['temperature']
weather_description = data['current']['weather_descriptions'][0]
print(f"The temperature in {location} is {temperature} degrees Celsius.")
print(f"The weather is {weather_description}.")
else:
print("Error occurred while fetching weather data.")

我创建了一个免费账户并从weatherstack获取了API,然后我将我的位置与API放入代码中。之后,我在VSCode中运行了代码。以下是输出结果:

ChatGPT中文站

现在我将简单解释代码的工作原理。首先,我们需要通过导入获取请求模块。请求模块将HTTP请求发送到Web服务器,然后从服务器接收响应。然后有两个变量,存储了我从weatherstack网站获取的API密钥和我的当前位置。位置可以是文字或纬度-经度格式。该代码通过将API密钥和位置作为查询发送请求到weatherstack API。

此外,如果状态码为200,即成功,则以JSON格式提取数据。然后从JSON中提取该位置的温度和天气信息,并在终端中打印出来。如果无法提取,则在终端中打印出错误消息。

2023-10-20 17:02:36 AI中文站翻译自原文