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.
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
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?
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.
python 3 please Define a function voweliest that takes as input a string and returns as...
python 3 please Define a function voweliest that takes as input a string and returns as output a tuple where the string that has the most vowels in it is the first element and the second is the number of vowels in that string. Note: don't worry about ties or capital letters Hint: consider defining and using a separate function that counts the number of vowels in a given string
Write a python function image compress() that takes one argument called filename, which is the name...
Write a python function image compress() that takes one argument called filename, which is the name of a file that contains a N × N (N-pixel by N-pixel) “grayscale bitmap image”. A “grayscale bitmap image” is an image of the following form where every pixel contains a grayscale color value between 0 − 255 (inclusive). Colour value 0 means that pixel should appear completely black and color value 255means completely white. Any other value in between stands for different shades...
Language: Python 3 Compose a function process which accepts a string filename. process should return a...
Language: Python 3 Compose a function process which accepts a string filename. process should return a list of records contained in the file. #define your function here # Create a blank list called `entries` and an empty string called `current_style`. # Open the file `filename`, read the data using readlines(), and close it. # Loop through each line of the file and do the following: # Strip the whitespace off of the ends of the line using the `strip` method....
Write a function that takes three integers, n, a and b and a filename and writes...
Write a function that takes three integers, n, a and b and a filename and writes to the file a list with n random integers between a and b. And then write a function that can read the files as generated above and return the values. language: python
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT