【python】统计文本中出现最多次的单词

题目来自 hacker.org 中的 Challenge '3280' [Coding] 。

要求找出 RFC 3280 中出现次数最多的长度为9的单词。

将 RFC 3280 的文本并保存到本地后用如下代码进行处理。

----

import re
text = open("in.txt",'r').read()
words = re.split('[^a-zA-Z]',text) 
di = {}
for word in words:
    if len(word)==9:
        di.setdefault(word,0)
        di[word]+=1
res = di.items()
print max(res,key=lambda x:x[1])
#res.sort(key=lambda x : x[1])
#for x in res: print x

----

open(name,'r') 以只读方式打开文件

file.open() 读取文件中的所有数据

re.split(pattern, string) 采用该正则表达式分裂字符串,并返回所得到的子列表

dict.setdefault(k[,d]) 字典中不含有给定键的情况下,设定默认值

dict.items() 将所有字典项以列表形式返回

max(iterable[, key=func]) 返回列表中的最大值,并可以指定比较函数


posted on 2014-03-18 18:46  电子幼体  阅读(1309)  评论(0编辑  收藏  举报

导航