Python对句子中的单词出现次数排序

出现次数相同的单词按照单词字母排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"""Count words."""

def count_words(s, n):
"""Return the n most frequently occuring words in s."""
words = s.split(" ")
# TODO: Count the number of occurences of each word in s
counters = {}
for word in words:
if word in counters:
counters[word] += 1
else:
counters[word] = 1
# TODO: Sort the occurences in descending order (alphabetically in case of ties)
top = sorted(counters.iteritems(), key=lambda d:(-d[1],d[0]))
##lambda中"-"为反序,意思是先把单词出现次数从大到小排列,
##然后再以单词的字母从小到大排列
# TODO: Return the top n words as a list of tuples (<word>, <count>)
top_n = top[:n]##返回前n个单词
return top_n

def test_run():
"""Test count_words() with some inputs."""
print count_words("cat bat mat cat bat cat", 3)
print count_words("betty bought a bit of butter but the butter was bitter", 3)

if __name__ == "__main__":
test_run()