此问题已经在这里有了答案:
我有一个sololearn课程的代码,该代码告诉我们文本文件中有多少个字母,并且可以正常工作,但是我想以其他方式打印。更具体地说,我想通过对文本中字母的数量而不是字母顺序进行打印。代码:
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)))
我的输出是:
a - 2.48%
b - 2.79%
c - 0.16%
d - 0.47%
e - 0.78%
f - 1.86%
.
.
.
但是我也想在开头看到最常见的字母,依此类推。难做吗?是否有捷径可寻?谢谢您的帮助。
下
from collections import Counter
with open('a.txt') as f:
counter = Counter(f.read())
print(counter.most_common())