0
sorting output
how can I sort the percentage output for every letter in the example "text analyzer" module "more types" in Python, descending or ascending. So that wether the list is starting with the highest or lowest percentage. What is the code for this function again? thanks for your help
1 ответ
0
Hi Rene-
Good question. You can create a list of character and percentage frequency tuples and then sort that list using the sort method. Here is example code of the text analyzer which will sort from highest frequency to lowest:
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()
#create a list of character and frequency tuples
char_freqs = []
for char in "abcdefghijklmnopqrstuvwxyz":
perc = 100 * count_char(text, char) / len(text)
char_freqs.append((char, round(perc, 2)))
#sort list on the second value of the tuples
char_freqs.sort(key=lambda x: x[1], reverse=True)
for char, freq in char_freqs:
print("{0} - {1}%".format(char, freq))