任务是读取文件,创建字典并打印出单词及其计数器值。下面的代码工作正常,但我似乎无法理解为什么在print_words()函数中,我无法将排序更改为:
words = sorted(word_count.values())
然后打印单词及其计数器,按计数器排序(单词在word_count []中的次数)。
def word_count_dict(filename):
word_count = {}
input_file = open(filename, 'r')
for line in input_file:
words = line.split()
for word in words:
word = word.lower()
if not word in word_count:
word_count[word] = 1
else:
word_count[word] = word_count[word] + 1
input_file.close()
return word_count
def print_words(filename):
word_count = word_count_dict(filename)
words = sorted(word_count.keys())
for word in words:
print word, word_count[word]
答案 0 :(得分:3)
如果按值(包括键)对输出进行排序,最简单的方法是使用items
参数排序key
(键值对),sorted
参数对words = sorted(word_count.keys())
for word in words:
print word, word_count[word]
进行排序值,然后迭代结果。因此,对于您的示例,您将替换:
from operator import itemgetter
with(将# key=itemgetter(1) means the sort key is the second value in each key-value
# tuple, meaning the value
sorted_word_counts = sorted(word_count.items(), key=itemgetter(1))
for word, count in sorted_word_counts:
print word, count
添加到模块顶部):
<DataType>string</DataType>
答案 1 :(得分:1)
首先要注意的是,字典不被认为是有序的,尽管这可能在将来发生变化。因此,最好将dict
转换为以某种方式排序的元组列表。
以下函数将帮助您将字典转换为按值排序的元组列表。
d = {'a': 5, 'b': 1, 'c': 7, 'd': 3}
def order_by_values(dct):
rev = sorted((v, k) for k, v in dct.items())
return [t[::-1] for t in rev]
order_by_values(d) # [('b', 1), ('d', 3), ('a', 5), ('c', 7)]