Question: This is a python code and then they ask to improve it . so the code will be first then the question. from os import

This is a python code and then they ask to improve it. so the code will be first then the question. from os import strerror
# Initialize 26 counters for each Latin letter.
# Note: we've used a comprehension to do that.
counters ={chr(ch): 0 for ch in range(ord('a'), ord('z')+1)}
file_name = input("Enter the name of the file to analyze: ")
try:
file = open(file_name, "rt")
for line in file:
for char in line:
# If it is a letter...
if char.isalpha():
# ... we'll treat it as lower-case and update the appropriate counter.
counters[char.lower()]+=1
file.close()
# Let's output the counters.
for char in counters.keys():
c = counters[char]
if c >0:
print(char,'->', c)
except IOError as e:
print("I/O error occurred: ", strerror(e.errno)) The previous code needs to be improved. It's okay, but it has to be better.
Your task is to make some amendments, which generate the following results:
the output histogram will be sorted based on the characters' frequency (the bigger counter should be presented first)
the histogram should be sent to a file with the same name as the input one, but with the suffix '.hist' (it should be concatenated to the original name)
Assuming that the input file contains just one line filled with:
cBabAa
samplefile.txt
the expected output should look as follows:
a ->3
b ->2
c ->1
Output
Tip: Use a lambda to change the sort order.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!