python实现指定目录下批量文件的单词计数:串行版本
来源:互联网 发布:剪力弯矩图软件 编辑:程序博客网 时间:2024/05/22 07:06
直接上代码。
练习目标:
1. 使用 Python 面向对象的方法封装逻辑和表达 ;
2. 使用异常处理和日志API ;
3. 使用文件目录读写API ;
4. 使用 list, map, tuple 三种数据结构 ;
5. lambda 、正则使用及其它。
下一篇将实现并发版本。
#-------------------------------------------------------------------------------# Name: wordstat_serial.py# Purpose: statistic words in java files of given directory by serial## Author: qin.shuq## Created: 08/10/2014# Copyright: (c) qin.shuq 2014# Licence: <your licence>#-------------------------------------------------------------------------------import reimport osimport timeimport loggingLOG_LEVELS = { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARN': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL}def initlog(filename) : logger = logging.getLogger() hdlr = logging.FileHandler(filename) formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s") hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(LOG_LEVELS['INFO']) return loggererrlog = initlog("error.log")infolog = initlog("info.log")class WordReading(object): def __init__(self, fileList): self.fileList = fileList def readFileInternal(self, filename): lines = [] try: f = open(filename, 'r') lines = f.readlines() infolog.info('[successful read file %s]\n' % filename) f.close() except IOError, err: errorInfo = 'file %s Not found \n' % filename errlog.error(errorInfo) return lines def readFile(self): allLines = [] for filename in self.fileList: allLines.extend(self.readFileInternal(filename)) return allLinesclass WordAnalyzing(object): ''' return Map<Word, count> the occurrence times of each word ''' wordRegex = re.compile("[\w]+") def __init__(self, allLines): self.allLines = allLines def analyze(self): result = {} lineContent = ''.join(self.allLines) matches = WordAnalyzing.wordRegex.findall(lineContent) if matches: for word in matches: if result.get(word) is None: result[word] = 0 result[word] += 1 return resultclass FileObtainer(object): def __init__(self, dirpath, fileFilterFunc=None): self.dirpath = dirpath self.fileFilterFunc = fileFilterFunc def findAllFilesInDir(self): files = [] for path, dirs, filenames in os.walk(self.dirpath): if len(filenames) > 0: for filename in filenames: files.append(path+'/'+filename) if self.fileFilterFunc is None: return files else: return filter(self.fileFilterFunc, files)class PostProcessing(object): def __init__(self, resultMap): self.resultMap = resultMap def sortByValue(self): return sorted(self.resultMap.items(),key=lambda e:e[1], reverse=True) def obtainTopN(self, topN): sortedResult = self.sortByValue() sortedNum = len(sortedResult) topN = sortedNum if topN > sortedNum else topN for i in range(topN): topi = sortedResult[i] print topi[0], ' counts: ', topi[1]if __name__ == "__main__": dirpath = "c:\\Users\\qin.shuq\\Desktop\\region_master\\src" starttime = time.time() fileObtainer = FileObtainer(dirpath, lambda f: f.endswith('.java')) fileList = fileObtainer.findAllFilesInDir() endtime = time.time() print 'ObtainFile cost: ', (endtime-starttime)*1000 , 'ms' starttime = time.time() wr = WordReading(fileList) allLines = wr.readFile() endtime = time.time() print 'WordReading cost: ', (endtime-starttime)*1000 , 'ms' starttime = time.time() wa = WordAnalyzing(allLines) resultMap = wa.analyze() endtime = time.time() print 'WordAnalyzing cost: ', (endtime-starttime)*1000 , 'ms' starttime = time.time() postproc = PostProcessing(resultMap) postproc.obtainTopN(30) endtime = time.time() print 'PostProcessing cost: ', (endtime-starttime)*1000 , 'ms'
0 0
- python实现指定目录下批量文件的单词计数:串行版本
- python实现指定目录下批量文件的单词计数:并发版本
- 目录下指定文件的批量清理
- Python实现批量执行同目录下的py文件
- 指定目录中批量查找指定后缀名的文件(Python)
- PYTHON 列出指定目录下的文件
- python如何批量修改指定目录下的文件名称
- shell批量删除指定目录下的文件
- Python脚本实现查找指定目录下包含指定关键字的文件
- python 删除指定目录下的指定名字的文件
- python实现单词计数的mapreduce
- python返回指定目录下指定的文件或文件夹
- Python实现查找指定目录下包括某关键字的所有文件脚本
- C++实现Linux下遍历指定目录下的文件
- 新手学Python 删除指定目录下的所有文件
- Python扫描指定目录下(包括子目录)的文件
- Python:在指定目录下查找满足条件的文件
- Python扫描指定目录下(包括子目录)的文件
- JSP 和 Servlet 工作原理
- 数据库Index 索引的优缺点
- twitch.tv 聊天特殊表情符号
- Oscache介绍
- close() was never explicitly called on database '/data/data/com.seehope.view/databases/note.db' 异常
- python实现指定目录下批量文件的单词计数:串行版本
- 深入理解JavaScript原型和闭包系列
- x86都得死:Intel平台SMM漏洞门事件
- 结构体操作的坏味道
- [书籍推荐]iOS开发
- AtomicLong源码分析
- 循环(迭代)与递归的区别
- android 获取系统默认路径
- socket类型及应用