python 查询一段字符中所有字母出现的次数,并倒序列出

 

 1 # coding:utf-8
 2 
 3 s = """
 4 Have you thought about what you want people to say about you after you’re gone? Can you hear the voice saying, “He was a great man.” Or “She really will be missed.” What else do they say?
 5 One of the strangest phenomena of life is to engage in a work that will last long after death. Isn’t that a lot like investing all your money so that future generations can bare interest on it? Perhaps, yet if you look deep in your own heart, you’ll find something drives you to make this kind of contribution---something drives every human being to find a purpose that lives on after death.
 6 """
 7 
 8 dit1 = {}
 9 for i in s:
10     dit1[i] = s.count(i)
11 #print dit1
12 
13 c1 = 0
14 dit2 = {}
15 for ii in dit1.keys():
16     if ii.isalpha() is True:
17         c1 = c1 +1
18         dit2[ii] = dit1[ii]
19 
20 print "all these have %d letter" % c1
21 print sorted(dit2.items(),key=lambda d:d[1],reverse=True)

 最后一句话是经常用于对dict类型进行排序的方法,其中reverse=True是倒序排列

posted @ 2015-08-04 12:06  沉下心学习  阅读(705)  评论(0编辑  收藏  举报