-1

I have a code from sololearn course which tell us how many letters is in text file and it is working fine, but I want to print this in other way. More specifically, I would like to print this by sorting of number of letter in a text, not alphabetically. The code:

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)))

And my out put is:

a - 2.48%
b - 2.79%
c - 0.16%
d - 0.47%
e - 0.78%
f - 1.86%
.
.
.

But I want too see the most common letter at the beginning and so on. Is it hard to do? Is there an easy way to do this? Thank you for a help.

Karollo
  • 45
  • 7
  • it might be easier to get the % of each letter by counting the occurance of the char and dividing by the length of the entire text. – Jeff R Oct 10 '19 at 20:49
  • This one may help you more: https://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples-by-the-element-at-a-given-index - add a line `stats=[]` before the loop, `stats.append((char,perc))` in the loop, and sort the result afterwards, `stats.sort(key=lambda t:t[1], reversed=True)` – tevemadar Oct 10 '19 at 21:05

1 Answers1

0

Below

from collections import Counter
with open('a.txt') as f:
    counter = Counter(f.read())
    print(counter.most_common())
balderman
  • 22,927
  • 7
  • 34
  • 52