Question

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 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

Remember:

  • DO NOT use more advanced functions than needed.
  • Make sure to include comments that explain all your steps (starts with #).
  • Run the program a few times to make sure it executes and meets all the requirements.

NYT2.txt file below:

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.

Homework Answers

Answer #1

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))

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Attached is a text file full of names. Write a program that prompts the user to...
Attached is a text file full of names. Write a program that prompts the user to type in a name. If the name appears in the list of names, the program prints a message indicating the name was found. If the name entered by the user is not in the database, the program prints a different message indicating the name was not found. The program will continue prompting the user and searching for names until the user enters "quit". The...
JAVA (Don't make it too complicated) Write a program that prompts the user for the name...
JAVA (Don't make it too complicated) Write a program that prompts the user for the name of a text file. The file should consist of a sequence of integers, one integer per line. The program will read in each line (using nextLine()), parse it as an int (using Integer.parseInt()), and report the number of values and their average. The average should be computed as a double. Your program should do some basic exception handling: (1) If the file cannot be...
Write a program in Python for a basic string extraction. The program should: Display a message...
Write a program in Python for a basic string extraction. The program should: Display a message stating its goal Prompt the user to enter any input Extract only the string characters from the input Display the extraction in lowercase For example, for the input "But, why?!?" the output should be but why Remember: Do not use more advanced functions than needed. Make sure to include comments that explain all your steps (starts with #). Run the program a few times...
SOLUTION IN C## Write a program that reads every line in a text file, line by...
SOLUTION IN C## Write a program that reads every line in a text file, line by line. Obtain the name of the existing file and the name of the new (copy) of the file by prompting the user for both of these on the console. Make sure that the original file exists and can be read. If not, display a warning message and allow the user to either abort the program or enter a new file name. If the name...
C++ Part B: (String) Program Description: Write a word search program that searches an input data...
C++ Part B: (String) Program Description: Write a word search program that searches an input data file for a word specified by the user. The program should display the number of times the word appears in the input data file. In addition, the program should count and display the number of grammatical characters in the input data file. Your program must do this by providing the following functions : void processFile(ifstream &inFile, string wordSearch, int &wordCount, int &grammaticalCount) ; (15%)...
Python Jupyter Notebook Write a program that prompts the user to enter his/her first name, last...
Python Jupyter Notebook Write a program that prompts the user to enter his/her first name, last name, and year of birth in a single string (in the format: fn;ln;yyyy), then calculates the age tell it to him/her after greeting him/her using the first name. Make sure to capitalize the user's first name, regardless of how he/she typed it in. Hint: review Exercise 1! Example: Enter your first name, last name, and birth year (in format fn;ln;yyyy): alex;smith;1994 Hi Alex, you...
Python programming Write a program that prompts the user to input the three coefficients a, b,...
Python programming Write a program that prompts the user to input the three coefficients a, b, and c of a quadratic equationax2+bx+c= 0.The program should display the solutions of this equation, in the following manner: 1. If the equation has one solution, display ONE SOLUTION:, followed by the solution, displayed with4 digits printed out after the decimal place. 2. If the equation has two real solutions, display TWO REAL SOLUTIONS:, followed by the two solutions, each displayed with4 digits printed...
Write a program In python of Jupiter notebook That prompts the user to enter his/her first...
Write a program In python of Jupiter notebook That prompts the user to enter his/her first name, last name, and year of birth in a single string (in the format: fn;ln;yyyy), then calculates the age tell it to him/her after greeting him/her using the first name. Make sure to capitalize the user's first name, regardless of how he/she typed it in. Hint: review Exercise 1! Example: Enter your first name, last name, and birth year (in format fn;ln;yyyy): alex;smith;1994 Hi...
Program Behavior Each time your program is run, it will prompt the user to enter the...
Program Behavior Each time your program is run, it will prompt the user to enter the name of an input file to analyze. It will then read and analyze the contents of the input file, then print the results. Here is a sample run of the program. User input is shown in red. Let's analyze some text! Enter file name: sample.txt Number of lines: 21 Number of words: 184 Number of long words: 49 Number of sentences: 14 Number of...
Python: Simple Banking Application Project Solution: • Input file: The program starts with reading in all...
Python: Simple Banking Application Project Solution: • Input file: The program starts with reading in all user information from a given input file. The input file contains information of a user in following order: username, first name, last name, password, account number and account balance. Information is separated with ‘|’. o username is a unique information, so no two users will have same username. Sample input file: Username eaglebank has password 123456, account number of BB12 and balance of $1000....
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT