Untitled

 avatar
unknown
python
5 months ago
4.9 kB
3
Indexable
"""Program for scraping weather data from CSV file."""

# Initing weather_data dict in order
# to handle the data from the CSV.
weather_data = {}

# Store the month names
# in a dict for easier
# access.
#
# Later found it this wasnt
# neccessary but I'm keeping
# this for now.
month_names = {
    1: "January",
    2: "February",
    3: "Mars",
    4: "April",
    5: "May",
    6: "June",
    7: "July",
    8: "August",
    9: "September",
    10: "October",
    11: "November",
    12: "December",
}


# Function for parsing weather
# data and add it to the dict.
def parse_data_add_to_weather_dict(ele: str):
    """
    Function for parsing rows from
    csv file that we parse into a
    dictionary with year as key
    and value as the weather data.
    """

    # Here I split the input into
    # year, month and data in order
    # to feed them into my dict and
    # contain them how I want.
    year = ele.split(";")[0][:4]
    month = ele.split(";")[0][5:7]
    data = ele.split(";")[-3::]

    # If the year is not a key in
    # the dict, I add it.
    if year not in weather_data:
        weather_data[year] = {}

    # If the month isn't within the
    # specified year key. I add the month.
    if month_names[int(month)] not in weather_data[year]:

        # I also keep a counter in the month dict
        # in order to easily get the average without
        # thinking of how many hours the specific month
        # contains.
        weather_data[year][month_names[int(month)]] = {"total_hours": 0, "data": []}

    # The above will catch every eventual problem.
    # Hence we can just add the data into the right
    # dict and list.
    weather_data[year][month_names[int(month)]]["data"].append(data)
    weather_data[year][month_names[int(month)]]["total_hours"] += 1


# Here we read the data from the
# CSV-file and parse it through our
# function. That also saves it into
# our weather_data.
with open("smhi-opendata_1_64510_20241007_132504.csv", "r", encoding="UTF-8") as f:
    for line in f:
        parse_data_add_to_weather_dict(line)


# We define a function for getting the average
# temperature.
def get_average_temp(year: str, month: int):
    """
    Calculating the average temp
    of a month.
    """
    temps = []

    # We keep track of the month name.
    month_name = month_names[month]

    # We check for each element within the
    # data list of the specific year and month
    for i in weather_data[year][month_name]["data"]:

        temps.append(
            float(i[1])
        )  # If it is contained we append index[1] which is the temeperature.

    # We then return the sum of all temps divided by the number of hours.
    # Getting the average of that specific month.
    return f"{sum(temps) / weather_data[year][month_name]['total_hours']:.2f}"


# Just a function for generating
# the output.
def return_statistics(year):
    """
    Function for composing data
    ready for outputting.
    """
    result = []

    # We iterate from month 1 -> last month
    for i in range(1, len(weather_data[year]) + 1):

        # We use the i in order to append the data from the first to
        # last month.
        #
        # In order to be the same as the example output we add
        # {i:02d} to have the same formatting.
        # 01, 02, 03 etc.
        result.append(f"Month {i:02d}: {get_average_temp(year, i)}°C")

    # We return the list.
    return result


# Main function
def main():
    """
    Main function
    """
    # Ask the user for input.
    while True:
        user_input = input("Enter the year to calculate the average temperature for: ")
        if not (int(user_input) < 1999 or int(user_input) > 2024):
            break
        else:
            print(f"Year {user_input} isn't available. Try a different year.")
    # We run the return_statistics that compiles
    # the data how we want and save it in "saved_results"
    # as a list.
    saved_result = return_statistics(user_input)

    # Printing Header prompt
    print(f"Average Temperatures for: {user_input}")

    # We print out each element within the
    # saved list.
    for i in saved_result:

        print(i)  # Each composed element

    # Here we start writing it to a file.
    with open(f"average_temperatures_{user_input}.txt", "w", encoding="UTF-8") as final:

        # Writing "header" text.
        final.write(f"Average Temperatures by month during: {user_input}\n\n")

        # We iterate through each element
        for result in saved_result:

            # And write it to the file, aswell
            # as a new line.
            final.write(f"{result}\n")

        # Lastly we ensure the user that the file has been written.
        print(f"Monthly averages saved to average_temperatures_{user_input}.txt")

    # Return 0 as good practice to ensure user program
    # ran successfully.
    return 0


main()
Editor is loading...
Leave a Comment