rric

numbers_from_file

Nov 27th, 2023 (edited)
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.00 KB | None | 0 0
  1. # Reads a CSV file containg weather data of the HISTALP project,
  2. # see http://www.zamg.ac.at/histalp/dataset/station/csv.php
  3. # Copyright 2022, 2023 Roland Richter                     [Mu: Python 3]
  4.  
  5.  
  6. def read_histalp_meta(file_name):
  7.     """Read a file in HISTALP format, and return a dictionary with meta data
  8.  
  9.    Example:
  10.    hist_meta = read_histalp_meta("HISTALP_AT_LIN_T01_1816_2022.csv")
  11.    hist_sttn = hist_meta['station']   # name of station is Linz
  12.  
  13.    Arguments:
  14.    file_name -- the name of the HISTALP file
  15.    """
  16.     csv_file = open(file_name, 'r')
  17.     hist_meta = {}
  18.  
  19.     for csv_line in csv_file:
  20.         # In HISTALP CSV files, a line starting with a '#' character is a comment;
  21.         # such lines starting may contain "key: value" entries, e.g.
  22.         # "# parameter: Mean temperature"
  23.         # "# source: http://www.zamg.ac.at/histalp"
  24.         # "# station: Linz-Stadt"
  25.         if csv_line.startswith('#'):
  26.             # The first ':' character always separates key from value; however,
  27.             # some values might contain the ':' character as well, as in
  28.             # "# source: http://www.zamg.ac.at/histalp"
  29.             # Hence, split into *at most* two parts: first the key, second the value.
  30.             csv_entries = csv_line[1:].split(':', 1)
  31.             if len(csv_entries) == 2:
  32.                 key = csv_entries[0].strip()
  33.                 hist_meta[key] = csv_entries[1].strip()
  34.         else:
  35.             pass
  36.  
  37.     csv_file.close()
  38.     return hist_meta
  39.  
  40.  
  41. def read_histalp_data(file_name, factor=1.0):
  42.     """Read a file in HISTALP format, and return a dictionary (keys: 1815, 2022,
  43.        ...) of dictionaries (keys: 'jan', 'feb', ...).
  44.  
  45.    Example:
  46.    hist_data = read_histalp_data("HISTALP_AT_LIN_T01_1816_2022.csv")
  47.    mean_tmpr = hist_data[1974]['mar']   # mean temperature of March 1974
  48.  
  49.    Arguments:
  50.    file_name -- the name of the HISTALP file
  51.    factor -- number to multiply all values with; only necessary for temperature (0.1)
  52.    """
  53.     csv_file = open(file_name, 'r')
  54.     hist_data = {}
  55.     is_first_line = True
  56.  
  57.     for csv_line in csv_file:
  58.         # ignore all lines starting with a '#' character, as these are comments
  59.         if csv_line.startswith('#'):
  60.             pass
  61.         else:
  62.             csv_entries = csv_line.strip().split(';')
  63.             # the first non-comment line contains the column headers
  64.             if is_first_line:
  65.                 column_header = csv_entries
  66.                 is_first_line = False
  67.             else:
  68.                 year = int(csv_entries[0])
  69.                 year_dict = {}
  70.                 # go through all entries of a line (except the first);
  71.                 # store the value (multiplied with the factor),
  72.                 # or 'nan' ('not a number') to indicate missing values
  73.                 for k in range(1, len(csv_entries)):
  74.                     entry = csv_entries[k]
  75.                     header = column_header[k]
  76.                     if entry != "999999":
  77.                         year_dict[header] = factor * float(entry)
  78.                     else:
  79.                         year_dict[header] = "nan"
  80.  
  81.                 hist_data[year] = year_dict
  82.  
  83.     csv_file.close()
  84.     return hist_data
  85.  
  86.  
  87. name = "HISTALP_AT_LIN_T01_1816_2022.csv"   # Mean temperature
  88. # name = "HISTALP_AT_LIN_R01_1852_2022.csv"   # Precipitation Totals
  89.  
  90. histalp_meta = read_histalp_meta(name)
  91. print(histalp_meta)
  92.  
  93. # Temperate data is given in units of 0,1 °C; convert it to ordinary °C
  94. if histalp_meta["unit"].startswith("0,1"):
  95.     histalp_data = read_histalp_data(name, 0.1)
  96.     histalp_meta["unit"] = "°C"
  97. else:
  98.     histalp_data = read_histalp_data(name)
  99.  
  100. print("Data available for", histalp_data.keys())
  101. year = int(input("Which year are you interested in? "))
  102.  
  103. if year not in histalp_data:
  104.     print("Sorry, no data for", year)
  105. else:
  106.     print("Year", year, "has entries for", histalp_data[year].keys())
  107.     month = input("Which month or period are you interested in? ")
  108.  
  109.     if month not in histalp_data[year]:
  110.         print("Sorry, no data for", month, year)
  111.     else:
  112.         param = histalp_meta["parameter"]
  113.         statn = histalp_meta["station"]
  114.         punit = histalp_meta["unit"]
  115.         print(param, "in", statn, ",", month, year, ":",
  116.               histalp_data[year][month], punit)
  117.  
  118.  
  119. # ----------------------------------------------------------------------
  120. # This program is free software: you can redistribute it and/or modify
  121. # it under the terms of the GNU General Public License as published by
  122. # the Free Software Foundation, either version 3 of the License, or
  123. # (at your option) any later version.
  124. #
  125. # This program is distributed in the hope that it will be useful,
  126. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  127. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  128. # GNU General Public License for more details.
  129. #
  130. # You should have received a copy of the GNU General Public License
  131. # along with this program.  If not, see <https://www.gnu.org/licenses/>.
  132.  
Advertisement
Add Comment
Please, Sign In to add comment