In: Computer Science
Define a function file_to_hist() which takes a string representing a filename, opens the file, reads its contents, closes the file,* and returns a histogram based on the letter frequencies in the given file. If no such file exists, your function should return an empty histogram (i.e., an empty dictionary {}). So for example, if the file nash.txt was in the same directory as char_hist3.py and had the following contents:
I have never seen a purple cow, And I never hope to see one. But I can tell you anyhow, I'd rather see than be one.
Then file_to_hist("nash.txt") would return the following histogram: {'r': 5, 'w': 2, 't': 5, ',': 2, 'u': 3, 'o': 7, 'B': 1, 'b': 1, 'p': 3, 's': 3, 'd': 2, 'l': 3, '\n': 4, 'A': 1, 'h': 5, '.': 2, 'n': 9, 'a': 6, 'v': 3, 'y': 2, ' ': 22, 'I': 4, "'": 1, 'c': 2, 'e': 18}.
You must use the provided make_hist() function in your definition.
You should be using with and as to make sure that the file gets closed automatically. You do not need to use .close()
def make_hist(string):
"""
returns a histogram based on the given
string.
str -> histogram
"""
hist = {}
for char in string:
if char in hist:
hist[char] += 1
else:
hist[char] = 1
return hist
Python program :
import os
def make_hist(string):
"""
returns a histogram based on the given string.
str -> histogram
"""
hist = {}
for char in string:
if char in hist:
hist[char] += 1
else:
hist[char] = 1
return hist
def file_to_hist(filename):
"""
this function returns a histogram based on the filename.
if the filename exists then it gives the histogram of that file.
otherwise it would return a empty dictionary {}.
"""
histogram = {}
if os.path.isfile(filename):
with open(filename,'r') as f: # open a file using with
lines = f.read() # read all content of file into lines
lines = lines + '\n'
histogram = make_hist(lines) # generates a histogram
return histogram
print(file_to_hist("nash.txt")) # testing the function file_to_hist
Input file : nash.txt
Output :