Question: Hi. Im just trying to adjust my code to make the output present itself differently. fname = input( Enter file name: ) words =
Hi. Im just trying to adjust my code to make the output present itself differently.
fname = input("Enter file name: ") words = {} fread = open(fname, "r") # collecting data into words dictionary and their frequency for line in fread: line = line.upper() if len(line) != 0: line = line.split() for word in line: if word.isalpha(): if word in words: words[word] += 1 else: words[word] = 1 fread.close() # sorting the dictionary based on values words = dict(sorted(words.items(), key=lambda x: x[1], reverse=True)) # printing the dictionary items form sorted dictionary for key, value in words.items(): print(key, value)
The file contains "How much wood would a woodchuck chuck if a woodchuck could chuck wood"
The program then outputs the following:
WOODCHUCK 2
WOOD 2
CHUCK 2
A 2
WOULD 1
MUCH 1
IF 1
HOW 1
COULD 1
Okay. So instead of this, I want the program to generate a text-based histogram for a list of labels/values read from the file. I want the histogram to show percentages of total input values. For example if there were 3 input with values 10, 5 and 5, 10 would show 50%
So for the above file, I want the output to be:
WOODCHUCK - 15%
WOOD - 15%
CHUCK - 15%
A - 15%
WOULD - 7%
MUCH - 7%
IF - 7%
HOW - 7%
COULD - 7%
Can anyone please lend a hand in changing my code?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
