''' DS2000 Spring 2020 Source code from class - file processing This example has structured data; the input file is a csv (comma-separated values) ''' import csv DATE = 0 TIME = 1 LAT = 2 LONG = 3 WIND = 4 PRESSURE = 5 CAT5 = 157 CAT4 = 130 CAT3 = 111 CAT2 = 96 def process_file(filename): ''' Function: process_file Parameter: Name of the file (a string) Returns: nested list of strings, the contents of the file Does: assumes the file to be read is a CSV file ''' data = [] counter = 0 with open(filename) as infile: csv_contents = csv.reader(infile, delimiter = ',') for row in csv_contents: if counter == 0: counter += 1 else: data.append(row) return data def when_landfall(data, long): ''' Function: when_landfall Parameter: nested list of strings, longitude to cross going west (float) Return: date/time when hurricane made landfall (string) Assumes: data is in chronological order ''' for row in data: if float(row[LONG]) < long: return row[DATE] + ' ' + row[TIME] return 'never' def worst_cat(data): ''' Function: worst_cat Parameters: nested list of strings for hurricane data Returns: The worst category hit (int) ''' worst_wind = 0 for row in data: if int(row[WIND]) > worst_wind: worst_wind = int(row[WIND]) # Now that we have the max wind, find the # category it belongs in (this is really similar # to the grading problem in HW3!!!) if worst_wind >= CAT5: return 5 elif worst_wind >= CAT4: return 4 elif worst_wind >= CAT3: return 3 elif worst_wind >= CAT2: return 2 else: return 1 def main(): # Step One: Read the file and save it in a nested list of strings hurricane_data = process_file('irma.csv') # Question: When did Irma first make landfall in Florida # (assumes the data are in chronological order) landfall = when_landfall(hurricane_data, -80) print('Irma made landfall at:', landfall) # Question: What category did Irma get to? cat = worst_cat(hurricane_data) print('At its worst, Hurricane Irma got to a category', cat) # Question: How big is the timeline that our data comes from? print('Data starts on', hurricane_data[0][DATE]) print('Data ends on', hurricane_data[-1][DATE]) main()