def count_words(s, n):
"""Return the n most frequently occuring words in s."""
# TODO: Count the number of occurences of each word in s
words = s.split()
counts = Counter(words)
# TODO: Sort the occurences in descending order (alphabetically in case of ties)
# TODO: Return the top n most frequent words.
return counts.most_common(n)
print count_words("betty bought a bit of butter but the butter was bitter", 3)
电流输出为:
^{pr2}$但必须的是:
[('butter', 2), ('a', 1), ('betty', 1)]
因为同样的频率,它必须按字母顺序排序。那么,如何按字母顺序按频率对列表“计数”进行排序呢?在
如Python docs所示
因此,计数为1的列在表中的顺序不能以任何特定的顺序得到保证,因为底层结构是
dict
。在如果你希望你的结果按字母顺序排列,你需要做更多的处理。在
这基本上是先通过获取所有结果。^{} ,然后sorts them按降序排列第二个参数(单词频率),然后按升序排列第一个参数(单词)。最后取前3个元素的slice作为结果。在
编辑:我意识到我没有正确排序,^{} 仅限于升序。在
您可以通过指定键函数来完成此操作
由于Python的sort是稳定的,另一种方法是先按字母顺序排序,然后按count进行反向排序
^{pr2}$首先使用bucket的概念计算所有单词,bucket由字典定义,其中键是单词,值是出现的次数。在
可以使用不带参数的sorted函数按键名排序。在
^{pr2}$然后按值从高到低排序:
相关问题 更多 >
编程相关推荐