+ 1

Please explain this code clearly.

def count_char(text, char): count = 0 for c in text: if c == char: count += 1 return count filename = input("Enter a filename: ") with open(filename) as f: text = f.read() for char in "abcdefghijklmnopqrstuvwxyz": perc = 100 * count_char(text, char) / len(text) print("{0} - {1}%".format(char, round(perc, 2)))

30th Aug 2020, 3:02 PM
Sadat Rahman
Sadat Rahman - avatar
2 Answers
+ 2
text variable contains all the file data count_char function takes that whole data as text and an alphabet ("abcdefgh...") And returns a count of the number of times it appeared in that text for loop iterates over the string sequence of alphabets assigning each character in that string to char variable ,so the loop runs 26 times for each alphabet Now perc calculate the percentage for each alphabet that appeared in the text like if "a" appeared 40 times then (40/length of text)*100
30th Aug 2020, 3:12 PM
Abhay
Abhay - avatar
+ 2
thanks
30th Aug 2020, 3:26 PM
Sadat Rahman
Sadat Rahman - avatar