Question

In: Computer Science

Define a function file_to_hist() which takes a string representing a filename, opens the file, reads its...

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

Solutions

Expert Solution

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 :


Related Solutions

Use python. redact_file: This function takes a string filename. It writes a new file that has...
Use python. redact_file: This function takes a string filename. It writes a new file that has the same contents as the argument, except that all of the phone numbers are redacted. Assume that the filename has only one period in it. The new filename is the same as the original with '_redacted' added before the period. For instance, if the input filename were 'myfile.txt', the output filename would be 'myfile_redacted.txt'. Make sure you close your output file.
C++ Only Create a function named PrintStudents, which takes a string input filename and an integer...
C++ Only Create a function named PrintStudents, which takes a string input filename and an integer minimum score value and a string output file name as a parameters. The function will read the student scores and names from the file and output the names of the students with scores greater than or equal to the value given. This function returns the integer number of entries read from the file. If the input file cannot be opened, return -1 and do...
Write a parameterized function that takes in a file name as a parameter, reads the file,...
Write a parameterized function that takes in a file name as a parameter, reads the file, calculates the factorial of each number, and displays a formatted output as follows: Factorial of 10 = 3628800 Factorial of 5 = 120
1. Write a program that prompts the user for a filename, then reads that file in...
1. Write a program that prompts the user for a filename, then reads that file in and displays the contents backwards, line by line, and character-by character on each line. You can do this with scalars, but an array is much easier to work with. If the original file is: abcdef ghijkl the output will be: lkjihg fedcba Need Help with this be done in only PERL. Please use "reverse"
Write a C++ function that reads a .csv file(file contains rows of string(name) and number) into...
Write a C++ function that reads a .csv file(file contains rows of string(name) and number) into a vector and loop through that vector and find the max number.
Write a C ++ program which opens a file and reads several numbers, utilizing the fscanf()...
Write a C ++ program which opens a file and reads several numbers, utilizing the fscanf() function. Can you add few comments with explanations what is going on?
Write a program that opens the file: "Lab6A_Data", reads all the values from the file, and...
Write a program that opens the file: "Lab6A_Data", reads all the values from the file, and calculates the following: A) The number of values in the file B) The sum of all the values in the file (a running total) C) The average of all the values in the file. D) The minimum value. E) The maximum value. F) The range of the data set of values. G) The number of times the value: '357' occurrs in the file. Display...
Java Code using Queue Write a program that opens a text file and reads its contents...
Java Code using Queue Write a program that opens a text file and reads its contents into a queue of characters, it should read character by character (including space/line change) and enqueue characters into a queue one by one. Dequeue characters, change their cases (upper case to lower case, lower case to upper case) and save them into a new text file (all the chars are in the same order as the original file, but with different upper/lower case) use...
Java Code using Stack Write a program that opens a text file and reads its contents...
Java Code using Stack Write a program that opens a text file and reads its contents into a stack of characters, it should read character by character (including space/line change) and push into stack one by one. The program should then pop the characters from the stack and save them in a second text file. The order of the characters saved in the second file should be the reverse of their order in the first file. Ex input file: Good...
In python Complete the function get_Astring(filename) to read the file contents from filename (note that the...
In python Complete the function get_Astring(filename) to read the file contents from filename (note that the test will use the file data.txt and data2.txt provided in the second and third tabs), strip off the newline character at the end of each line and return the contents as a single string.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT