练习:统计一句英文中单词出现的次数,并排序输出到html页面
#!/usr/bin/env python#coding:utf-8content="who have touched their lives Love begins with a smile grows with a kiss and ends with a tear The brightest future will always be based on a forgotten past you can’t go on well in lifeuntil you let go of your past failures and heartaches"# 将文本拼接成word:num的字典形式#循环列表,并且将单词作为字典的key,每出现一次这个单词,key+1result = {}for s in content.split(" "): if s in result: result[s] +=1 else: result[s] = 1#print result# 字典翻转拼接为num:word的字典res = {}for k,v in result.items(): res.setdefault(v,[]) res[v].append(k)#print rescount = 0f = open('tongji.html','a+')f.write("
次数 | 单词")while count < 4: key = max(res.keys()) print "出现了%s次的单词:%s" % (key,res[key]) for word in res[key]: f.write(' | %s | %s' % (key,word)) res.pop(key) count = count +1f.write("")f.close() |
---|