# # file_dict.py # # Examples of functions that perform file-processing # and/or use a dictionary. # # see track_results.txt for a sample file of track-meet results # def extract_results(filename, target_school): """ extracts and prints track-meet results for the specified target_school from the text file named filename. inputs: filename is a string specifying the name of a comma-delimited text file containing track-meet results. Each line of the file should have the following form: athlete name,school name,event,result target_school is a string specifying the name of the school whose results should be extracted """ file = open(filename, 'r') for line in file: line = line[:-1] # chop off newline at end fields = line.split(',') athlete = fields[0] school = fields[1] event = fields[2] result = fields[3] if school == target_school: print(athlete, event, result) file.close() def school_counts(filename): """ processes a text file containing track-meet results and uses a dictionary to compute and print the number of results for each school in the file input: filename is a string specifying the name of a comma-delimited text file containing track-meet results. Each line of the file should have the following form: athlete name,school name,event,result """ file = open(filename, 'r') counts = {} for line in file: fields = line.split(',') school = fields[1] if school not in counts: counts[school] = 1 else: counts[school] += 1 file.close() print('There are', len(counts), 'schools in all.') for school in counts: print(school, 'has', counts[school], 'result(s).') def word_frequencies(filename): """ uses the text file with the specified filename to create and return a dictionary of word frequencies for words in that text file. input: filename is a string specifying the name of a text file, which we assume is in the same folder as this Python file """ file = open(filename, 'r') text = file.read() # read it all in at once! file.close() words = text.split() d = {} for word in words: if word not in d: d[word] = 1 else: d[word] += 1 return d