python统计字符串中不同单词的数量

通过python对字符串中的所有单词进行统计,统计出每个单词出现的次数,并显示出现次数最多的单词

text = "ga bu zo meuh ga zo bu meuh meuh ga zo zo meuh zo bu zo" 

items = text.split(' ')  
counters = {}  
for item in items:  
    if item in counters:  
        counters[item] += 1 
    else:  
        counters[item] = 1 
print "Count of different word:" 
print counters  
print "Most popular word:" 
print sorted([(counter,word) for word,counter in counters.items()],reverse=True)[0][1]  

   
#显示结果:  
Count of different word:  
{'bu': 3, 'zo': 6, 'meuh': 4, 'ga': 3}  
Most popular word:  
zo

该代码片段来自于: http://www.sharejs.com/codes/python/1871

posted @ 2013-03-19 21:50  野草Leo  阅读(4030)  评论(0编辑  收藏  举报