Python 有没有办法清理这个脚本?

Python 有没有办法清理这个脚本?,python,Python,该脚本花了一天时间使用python中的Open Weather Map API,收集天气信息并将其写入“Weather.txt”文件。代码可以工作,但是,我觉得它可能需要一些清理,但我不知道如何正确清理它。您可能可以从我的代码中看出,但我仍在学习python,所以任何提示都将非常棒 import requests from datetime import date def GET_WEATHER(): global json_data global temp glo

该脚本花了一天时间使用python中的Open Weather Map API,收集天气信息并将其写入“Weather.txt”文件。代码可以工作,但是,我觉得它可能需要一些清理,但我不知道如何正确清理它。您可能可以从我的代码中看出,但我仍在学习python,所以任何提示都将非常棒

import requests
from datetime import date


def GET_WEATHER():

    global json_data
    global temp
    global temp_max
    global temp_min
    global humidity
    global pressure
    global today

    today = date.today()
    CITY = "Atlanta"
    API_KEY = "c6847d221f9667d8ff9a2701e3bd05ec"
    UNITS = "Imperial"
    URL = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={API_KEY}&units={UNITS}'


    json_data = requests.get(URL).json()
    temp = json_data['main']['temp']
    temp_max = json_data['main']['temp_max']
    temp_min = json_data['main']['temp_min']
    humidity = json_data['main']['humidity']
    pressure = json_data['main']['pressure']


def INFO_DUMP():
    global json_data
    global temp
    global temp_min
    global humidity
    global pressure
    global today

    with open('weather.txt','w') as f:
        f.write(str(today))
        f.write('\n')
        f.write("Current Temperature: ")
        f.write(str(temp))
        f.write('\n')
        f.write("Max Temerature: ")
        f.write(str(temp_max))
        f.write('\n')
        f.write("Minimum Temerature: ")
        f.write(str(temp_min))
        f.write('\n')
        f.write("Humidity: ")
        f.write(str(humidity))
        f.write("%")
        f.write('\n')

GET_WEATHER()
INFO_DUMP()

您根本不需要
INFO\u DUMP
函数,也不使用
global
变量。如果没有必要,建议不要使用该变量

更好的解决方案:

import requests
from datetime import date


def get_weather(city, units):
    today = date.today()
    API_KEY = "c6847d221f9667d8ff9a2701e3bd05ec"
    URL = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units={units}'

    json_data = requests.get(URL).json()

    main = json_data['main']
    temp = main['temp']
    temp_max = main['temp_max']
    temp_min = main['temp_min']
    humidity = main['humidity']
    pressure = main['pressure']

    with open('weather.txt', 'w') as f:
        f.write(str(today) + '\n' + "Current Temperature: "
                + str(temp) + '\n' + "Max Temerature: " +
                str(temp_max) + '\n' + "Minimum Temerature: " + str(temp_min)
                + '\n' + "Humidity: " + str(humidity) + "%" + '\n')

我投票结束这个问题,因为它属于codereview.stackexchange.com