Weather_Man Project-knowledgecityfree

Weather Man Project


Weatherman project with python getting data from weather files through python

import os
import math
import calendar
import re
import argparse
import csv  

max_temps = []
min_temps = []
mean_humids = []
dates = []

class WeatherMan:
    def __init__(self, year, month=None, file_path=None, graph=False, bar=False):
        self.year = int(year)
        self.month = int(month) if month else None
        self.file_path = file_path
        self.graph = graph
        self.bar = bar

       

    def filter_file(self, file_name):
        if self.month is not None:
            return f"Murree_weather_{self.year}_{calendar.month_abbr[self.month]}" in file_name
        else:
            return f"Murree_weather_{self.year}_" in file_name

    def process_data(self):
        file_list = os.listdir(self.file_path)

        filter_data = list(filter(self.filter_file, file_list))

        if not filter_data:
            if self.month is not None:
                print(f"No data available for {calendar.month_name[self.month]}, {self.year}")
            else:
                print(f"No data available for {self.year}")
            return

       

        for content in filter_data:
            content_data = os.path.join(self.file_path, content)

            with open(content_data, 'r') as file:
                csv_reader = csv.reader(file)
                header = next(csv_reader)
                # print(header)

                search_values = ['PKT', 'PKST']
                PKT_index = next((row for row, x in enumerate(header) if x in search_values), None)
                max_temp_index = header.index('Max TemperatureC')
                min_temp_index = header.index('Min TemperatureC')
                mean_Humidity_index = header.index('Max Humidity')

                for line in csv_reader:
                 if len(line) > max_temp_index and len(line) > min_temp_index and len(line) > mean_Humidity_index and len(line) > PKT_index:
                   try:
                    max_temp = int(line[max_temp_index])
                    min_temp = int(line[min_temp_index])
                    mean_humid = int(line[mean_Humidity_index])
                    date = line[PKT_index]

                    max_temps.append(max_temp)
                    min_temps.append(min_temp)
                    mean_humids.append(mean_humid)
                    dates.append(date)
               
                   except ValueError as e:
                        # print(f"Error processing line {line}: {e}")

                 
                    # use color for graph
                    Red = '\033[91m'
                    Blue = '\033[94m'


       

        if self.graph:
           print("Temperature Graph:")
           for temp in range(max(max_temps)):
             print(Red + '+', end= '')
           print(f'{max(max_temps)}°C')
           for temps in range(min(min_temps)):
             print(Blue +'+', end= '')
           print(f'{min(min_temps)}°C')
        elif self.bar:
            print("Temperature Bar Chart:")
            for plus in range(min(min_temps)):
              print(Blue +'+', end= '')
            for plus_2 in range(max(max_temps)):
              print(Red + '+', end= '')
            print(f"{max(max_temps)}°C - {min(min_temps)}°C")

        else:
            count = max(max_temps)
            count_1 = min(min_temps)
            count_2 = sum(mean_humids) / len(mean_humids)
            dates_value = dates[max_temps.index(count)].split('-')
            dates_values = dates[min_temps.index(count_1)].split('-')
            dates_middle_value = int(dates_value[1])
            dates_middles_value = int(dates_values[1])
       
            if self.month is not None:
              print(f"Data for {calendar.month_name[self.month]}, {self.year}:")
              print(f"Highest Temperature {count}°C ")
              print(f"Lowest Temperature  {count_1}°C ")
              print(f"Average Max Humidity {math.ceil(count_2)}%\n")
            else:
              print(f"Data for {self.year}:")
              print(f"Highest Temperature {count}°C on {calendar.month_name[dates_middle_value]}")
              print(f"Lowest Temperature  {count_1}°C on {calendar.month_name[dates_middles_value]}")
              print(f"Average Max Humidity {math.ceil(count_2)}%\n")

       

def arguments():
    parser = argparse.ArgumentParser(description='Weather Man Script')
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-y', '--year', help='Give the data of the Year')
    group.add_argument('-m', '--year-month', help='Give data for Year and month')
    parser.add_argument('-p', '--path', required=True, help='Path to weather files')
    parser.add_argument('-g', '--graph', action='store_true', help='Display temperature graph')
    parser.add_argument('-b', '--bar', action='store_true', help='Display temperature bar chart')

    args = parser.parse_args()

    if args.year and args.year_month:
        print("Error: Please provide either -y/--year or -c/--year-month, not both.")
        exit(1)

    if args.year:
        separate = re.split(r'[-/]', args.year)
        year = int(separate[0])
        month = None
    elif args.year_month:
        separate = re.split(r'[-/]', args.year_month)
        year = int(separate[0])
        month = int(separate[1]) if len(separate) == 2 else None
    else:
        year = None
        month = None
    weather_man = WeatherMan(year, month,args.path,args.graph,args.bar)
    weather_man.process_data()

if __name__ == "__main__":
    arguments()

No comments

Powered by Blogger.