0

Explain this python code please...

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))) REALLY THANK YOU. https://code.sololearn.com/380/#py

30th Oct 2017, 7:58 PM
Dariush Shiri
Dariush Shiri - avatar
2 Answers
+ 8
It first defines the count_char() method which counts a given character within a text. Then it opens a file for reading and reads it. The main iterator goes over a collection of letters and counts for occurrences of each of them in the text. Finally, it prints out those occurrences in a percentage format.
30th Oct 2017, 8:59 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 3
In short: It simply reads all the lines in a file, and then iterates through all characters (counting them along the way). It then prints the occurrence (in percentage) of each letter. The function "count_char" counts the amount of characters in a given string "text" that match a given character "char". The rest of the count has Python opening a file, storing it into a variable "text", then looping through every letter of the alphabet and the text string, counting its occurrence.
30th Oct 2017, 8:58 PM
Sapphire