我正在计数txt文件中的所有字母,然后按降序显示 [英] I'm trying to count all letters in a txt file then display in descending order
问题描述
如标题所示:
到目前为止,我在我的代码中工作,但我无法按顺序显示信息。目前,它只是随机显示信息。
So far this is where I'm at my code does work however I am having trouble displaying the information in order. Currently it just displays the information randomly.
def frequencies(filename):
infile=open(filename, 'r')
wordcount={}
content = infile.read()
infile.close()
counter = {}
invalid = "‘'`,.?!:;-_\n—' '"
for word in content:
word = content.lower()
for letter in word:
if letter not in invalid:
if letter not in counter:
counter[letter] = content.count(letter)
print('{:8} appears {} times.'.format(letter, counter[letter]))
任何帮助将不胜感激。
推荐答案
按降序显示需要在搜索循环之外,否则将在遇到时显示。
Displaying in descending order needs to be outside your search-loop otherwise they will be displayed as they are encountered.
使用内置的 已排序
(您需要设置 reverse
-argument!)
Sorting in descending order is quite easy using the built-in sorted
(you'll need to set the reverse
-argument!)
但是python是包含电池,而且已经有一个< a href =https://docs.python.org/library/collections.html#collections.Counter =nofollow noreferrer> 计数器
。所以它可以是简单的:
However python is batteries included and there is already a Counter
. So it could be as simply as:
from collections import Counter
from operator import itemgetter
def frequencies(filename):
# Sets are especially optimized for fast lookups so this will be
# a perfect fit for the invalid characters.
invalid = set("‘'`,.?!:;-_\n—' '")
# Using open in a with block makes sure the file is closed afterwards.
with open(filename, 'r') as infile:
# The "char for char ...." is a conditional generator expression
# that feeds all characters to the counter that are not invalid.
counter = Counter(char for char in infile.read().lower() if char not in invalid)
# If you want to display the values:
for char, charcount in sorted(counter.items(), key=itemgetter(1), reverse=True):
print(char, charcount)
计数器已经有一个 most_common
方法,但是您想要显示所有字符和数字,因此在这种情况下不太合适。然而,如果你只想知道x最常见的数值,那么它将是合适的。
The Counter already has a most_common
method but you want to display all characters and counts so it's not a good fit in this case. However if you only want to know the x most common counts then it would suitable.
这篇关于我正在计数txt文件中的所有字母,然后按降序显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!