我很困惑。我正在向我的程序中输入一个文本文件。在读完每个字符(低+大写=相同的字符)并计算它们之后,我需要对它们进行排序(从频繁到不频繁)。目前我正在获得每个角色的结果/计数,但我无法弄清楚如何对结果进行排序。我尝试的任何事情都会弄乱我目前的结果。
我现在有这个:
import string
z = open("file_location", 'r')
letters = {}
def count_letter(c):
if c in letters:
letters[c] += 1 # if letter in letters add one
else:
letters[c] = 1 # if letter not in letters set add letter to dictionary object
def print_letters(letters):
for x,y in letters.items():
print ("%s - [%s]" % (x, y)) # print out count for each letter
#Run code
for line in z: # for each line in input file
for letter in line: # for each letter in line
letter = letter.strip()
letter = letter.lower()
count_letter(letter) # tally a count of each letter
print_letters(letters)
答案 0 :(得分:0)
试试这个
letters_sorted = sorted(letters.iteritems(), key=operator.itemgetter(1), reverse=True)