python实现指定目录下批量文件的单词计数:串行版本
直接上代码。
练习目标:
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 re
import os
import time
import logging LOG_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 logger errlog = 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 allLines class 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 result class 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'
python实现指定目录下批量文件的单词计数:串行版本的更多相关文章
- python实现指定目录下批量文件的单词计数:并发版本
在 文章 <python实现指定目录下批量文件的单词计数:串行版本>中, 总体思路是: A. 一次性获取指定目录下的所有符合条件的文件 -> B. 一次性获取所有文件的所有文件行 - ...
- [python] 在指定目录下找文件
import os # 查找当前目录下所有包含关键字的文件 def findFile(path, filekw): return[os.path.join(path,x) for x in os.li ...
- python实现指定目录下JAVA文件单词计数的多进程版本
要说明的是, 串行版本足够快了, 在我的酷睿双核 debian7.6 下运行只要 0.2s , 简直是难以超越. 多进程版本难以避免大量的进程创建和数据同步与传输开销, 性能反而不如串行版本, 只能作 ...
- python查找指定目录下所有文件,以及改文件名的方法
一: os.listdir(path) 把path目录下的所有文件保存在列表中: >>> import os>>> import re>>> pa ...
- PHP 批量获取指定目录下的文件列表(递归,穿透所有子目录)
//调用 $dir = '/Users/xxx/www'; $exceptFolders = array('view','test'); $exceptFiles = array('BaseContr ...
- python获取指定目录下所有文件名os.walk和os.listdir
python获取指定目录下所有文件名os.walk和os.listdir 觉得有用的话,欢迎一起讨论相互学习~Follow Me os.walk 返回指定路径下所有文件和子文件夹中所有文件列表 其中文 ...
- Python获取指定目录下所有子目录、所有文件名
需求 给出制定目录,通过Python获取指定目录下的所有子目录,所有(子目录下)文件名: 实现 import os def file_name(file_dir): for root, dirs, f ...
- PHP 获取指定目录下所有文件(包含子目录)
PHP 获取指定目录下所有文件(包含子目录) //glob — 寻找与模式匹配的文件路径 $filter_dir = array('CVS', 'templates_c', 'log', 'img', ...
- iOS案例:读取指定目录下的文件列表
// // main.m // 读取指定目录下的文件列表 // // Created by Apple on 15/11/24. // Copyright © 2015年 Apple. All rig ...
随机推荐
- php mysql连接例子
<?PHP @$conn = mysql_connect("127.0.0.1","root",""); //返回false或reso ...
- http://blinkfox.com/shi-yong-spring-aoplai-tong-ji-fang-fa-de-zhi-xing-shi-jian/
http://blinkfox.com/shi-yong-spring-aoplai-tong-ji-fang-fa-de-zhi-xing-shi-jian/ spring-aop.xml @Com ...
- Aspose.Words 开发时遇到的问题
问题一 Document doc.Save(Response, "学员报名表.pdf", ContentDisposition.Inline, null); 执行后没有效果,因为异 ...
- iOS工程如何支持64-bit
苹果在2014年10月20号发布了一条消息:从明年的二月一号开始,提交到App Store的应用必须支持64-bit.详细消息地址为:https://developer.apple.com/news/ ...
- js实例代码
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 官方教程:教你用好微信JS-SDK接口
微信开放JS-SDK接口,开发者和行业用户可谓是欢欣鼓舞.奔走相告,目测将激起一大波第三方开发商的创新产品!真真是H5开发者的利好!但也有用户表示,还不了解JS-SDK接口到底是啥,究竟怎么用.现在, ...
- Java Lock ReentrantLock ReentrantReadWriteLock
Lock与Synchronized的区别: 1)Lock是一个接口,而synchronized是Java中的关键字,synchronized是内置的语言实现: 2)synchronized在发生异 ...
- strtok&strsep
strtok,strtok_r,strsep--extract tokens from strings Tje strsep() function was introduced as a replac ...
- 三层交换机+二层交换机配置VLAN相互访问
使用思科模拟软件Cisco Packet Tracer Student,软件功能有限,只能架设简单的网络架构,适合初学者使用.
- [RGEOS]支持栅格数据读取和显示
SharpMap真的很强大,这里通过改造GdalRasterLayer类实现了在RGeos项目中支持栅格图像的读取和显示,同时支持影像的无级缩放. GdalRasterLayer通过读取FWTools ...