Question

In: Computer Science

Write a program that prompts the user for a file name, make sure the file exists...

Write a program that prompts the user for a file name, make sure the file exists and then reads through the file, counts the number of times each word appears and outputs the word count in a sorted order from high to low.

The program should:

  • Display a message stating its goal
  • Prompt the user to enter a file name
  • Check that the file can be opened and if not ask the user to try again (hint: use the try/except structure)
  • Count the number of times each word appears in the file, regardless if in lowercase or uppercase (hint: use dictionaries and the lower() function)
  • Display the word count in order from high to low
  • Bonus: if a few words have the same count, sort the display in an alphabetic order
  • For example, for the attached file NYT2.txt, the top five words in the output should be

the - 7

in - 6

to - 5

and - 4

of - 4

File Name: NYT2.txt

File Content:

Fact-Checking Trump’s Orlando Rally: Russia, the Wall and Tax Cuts
President Trump delivered remarks in Florida in a formal start to his re-election effort.
Deutsche Bank Faces Criminal Investigation for Potential Money-Laundering Lapses        
Federal authorities are focused on whether the bank complied with anti-money-laundering laws, including in its review of transactions linked to Jared Kushner.
Five NY1 Anchorwomen Sue Cable Channel for Age and Gender Discrimination
The women, including Roma Torre, say their careers were derailed after Charter Communications bought New York’s hometown news station in 2016.
Hypersonic Missiles Are Unstoppable. And They’re Starting a New Global Arms Race.
The new weapons — which could travel at more than 15 times the speed of sound with terrifying accuracy — threaten to change the nature of warfare.
Nxivm’s Keith Raniere Convicted in Trial Exposing Sex Cult’s Inner Workings
Mr. Raniere set up a harem of sexual “slaves” who were branded with his initials and kept in line by blackmail.
Jamal Khashoggi Was My Fiancé. His Killers Are Roaming Free.
Washington hasn’t done enough to bring the murdered Saudi columnist’s killers to justice.

Solutions

Expert Solution

If you have any doubts, please give me comment...

import string

def countWords(fname):

    words = {}

    fp = open(fname, "r")

    for line in fp.readlines():

        line = line.lower().translate(str.maketrans('','', string.punctuation))

        for w in line.split():

            if w not in words:

                words[w] = 0

            words[w] += 1

    fp.close()

    return words

fname = input("Enter file: ")

frequency = countWords(fname)

sorted_frequency = sorted(frequency.items(), key = lambda kv:(kv[1], kv[0]), reverse=True)

for (word, freq) in sorted_frequency[:5]:

    print(word+" : "+str(freq))


Related Solutions

Write a program that prompts the user for a file name, make sure the file exists...
Write a program that prompts the user for a file name, make sure the file exists and if it does reads through the file, count the number of times each word appears and then output the word count in a sorted order from high to low. The program should: Display a message stating its goal Prompt the user to enter a file name Check that the file can be opened and if not ask the user to try again (hint:...
In Python write a program that prompts the user for a file name, make sure the...
In Python write a program that prompts the user for a file name, make sure the file exists and if it does reads through the file, count the number of times each word appears and then output the word count in a sorted order from high to low. The program should: Display a message stating its goal Prompt the user to enter a file name Check that the file can be opened and if not ask the user to try...
Write a program that prompts the user to enter a file name, then opens the file...
Write a program that prompts the user to enter a file name, then opens the file in text mode and reads names. The file contains one name on each line. The program then compares each name with the name that is at the end of the file in a symmetrical position. For example if the file contains 10 names, the name #1 is compared with name #10, name #2 is compared with name #9, and so on. If you find...
Question 1: Write a Java program that prompts the user to input a file name (existing...
Question 1: Write a Java program that prompts the user to input a file name (existing text file), then calculate and display the numbers of lines in that file. Also calculate and display the length of the longest line in that file. For example, if the input file has the following lines: Hello This is the longest line Bye The output should be: The file has 3 lines. The longest line is line 2 and it has 24 characters. Test...
C++ Write a program that prompts for a file name and then reads the file to...
C++ Write a program that prompts for a file name and then reads the file to check for balanced curly braces, {; parentheses, (); and square brackets, []. Use a stack to store the most recent unmatched left symbol. The program should ignore any character that is not a parenthesis, curly brace, or square bracket. Note that proper nesting is required. For instance, [a(b]c) is invalid. Display the line number the error occurred on. These are a few of the...
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"
Part A In PyCharm, write a program that prompts the user for their name and age....
Part A In PyCharm, write a program that prompts the user for their name and age. Your program should then tell the user the year they were born. Here is a sample execution of the program with the user input in bold: What is your name? Amanda How old are you? 15 Hello Amanda! You were born in 2005. Write the program. Format your code using best practices. Refer to the zyBooks style guide, if needed, to use proper naming...
Python: Write a program that asks the user for the name of a file. The program...
Python: Write a program that asks the user for the name of a file. The program should display the contents of the file line by line.
Question: Write a program in python that reads in the file climate_data_2017_numeric.csv and prompts the user...
Question: Write a program in python that reads in the file climate_data_2017_numeric.csv and prompts the user to enter the name of a field (other than Date), and then outputs the highest and lowest values recorded in that field for the month of August. The file climate_data_2017_numeric.csv contains the following fields: Date Minimum temperature (C) Maximum temperature (C) Rainfall (mm) Speed of maximum wind gust (km/h) 9am Temperature (C) 9am relative humidity (%) 3pm Temperature (C) 3pm relative humidity (%) Expected...
Write a program that asks the user to enter the name of a file, and then...
Write a program that asks the user to enter the name of a file, and then asks the user to enter a character. The program should count and display the number of times that the specified character appears in the file. Use Notepad or another text editor to create a sample file that can be used to test the program. Sample Run java FileLetterCounter Enter file name: wc4↵ Enter character to count: 0↵ The character '0' appears in the file...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT