Write a function that analyzes how many times the characters \'a\' to \'z\' occu
ID: 3809916 • Letter: W
Question
Write a function that analyzes how many times the characters 'a' to 'z' occur in a file, and writes those counts, as well as their frequencies, to a specified output file. function () = char Freq (inputFile, outputFile) % % input File specifies the file whose characters should % be analyzed. % % output File will contain the counts of the characters % 'a' to 'z' found in the input file Will % contain the frequency of each character. % Frequency is the number of occurrences % divided by the total characters in the file. % % If inputFile or outputFile cannot be opened, the $ function will print a descriptive error message and % return. %Explanation / Answer
#writing the code in python,save this python code as .py file in a folder and in the same folder create input.txt and output.txt files and place the content in input.txt file
#importing the required libraries
import os
from collections import Counter
def charFreq(inputFile, outputFile):
if not (os.path.exists(inputFile)):
return "Input File Does not exist"
if not (os.path.exists(outputFile)):
return "Output File Does not exist"
with open(inputFile,mode='r') as g:
all = g.read()
counts = Counter()
for char in all:
#checking the character whether it is alphabet or not
if ord(char) in alphabets:
counts[char] +=1
frequencies = {}
for key in counts.keys():
frequencies[key] = counts.get(key)/sum(counts.values())
with open(outputFile,mode = 'w') as h:
for i in counts.keys():
freq = frequencies[i]
count = counts.get(i)
h.write(str(i) + " -> " + "Frequency : " +str(freq)+ " Count : " +str(count) +" ")
#storing the alphabets
alphabets = list(range(65, 91)) + list(range(97, 123))
charFreq("input.txt","Output.txt")
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.