def compare(a,b): if b[1]>a[1]: return 1 elif b[1]==a[1]: if a[0]>b[0]: return 1 else: return -1 else: return -1 def count_words(s, n): """Return the n most frequently occuring words in s.""" ##Count the number of occurences of each word in s d ={} for word in s.split(): d[word] =d.get(word,0)+1 #D[k] if k in D, else d. d defaults to None ##Sort the occurences in descending order (alphabexcally in case of xes) #d =sorted(d.iteritems(),key=lambda t:t[1],reverse=True) #print "按值排序,从大到小 d=", d vk =sorted(d.items(),cmp=compare) return vk[:n] ##Return the top n words as a list of tuples (<word>, <count>) 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()