直接上代码。

练习目标:

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实现指定目录下批量文件的单词计数:串行版本的更多相关文章

  1. python实现指定目录下批量文件的单词计数:并发版本

    在 文章 <python实现指定目录下批量文件的单词计数:串行版本>中, 总体思路是: A. 一次性获取指定目录下的所有符合条件的文件 -> B. 一次性获取所有文件的所有文件行 - ...

  2. [python] 在指定目录下找文件

    import os # 查找当前目录下所有包含关键字的文件 def findFile(path, filekw): return[os.path.join(path,x) for x in os.li ...

  3. python实现指定目录下JAVA文件单词计数的多进程版本

    要说明的是, 串行版本足够快了, 在我的酷睿双核 debian7.6 下运行只要 0.2s , 简直是难以超越. 多进程版本难以避免大量的进程创建和数据同步与传输开销, 性能反而不如串行版本, 只能作 ...

  4. python查找指定目录下所有文件,以及改文件名的方法

    一: os.listdir(path) 把path目录下的所有文件保存在列表中: >>> import os>>> import re>>> pa ...

  5. PHP 批量获取指定目录下的文件列表(递归,穿透所有子目录)

    //调用 $dir = '/Users/xxx/www'; $exceptFolders = array('view','test'); $exceptFiles = array('BaseContr ...

  6. python获取指定目录下所有文件名os.walk和os.listdir

    python获取指定目录下所有文件名os.walk和os.listdir 觉得有用的话,欢迎一起讨论相互学习~Follow Me os.walk 返回指定路径下所有文件和子文件夹中所有文件列表 其中文 ...

  7. Python获取指定目录下所有子目录、所有文件名

    需求 给出制定目录,通过Python获取指定目录下的所有子目录,所有(子目录下)文件名: 实现 import os def file_name(file_dir): for root, dirs, f ...

  8. PHP 获取指定目录下所有文件(包含子目录)

    PHP 获取指定目录下所有文件(包含子目录) //glob — 寻找与模式匹配的文件路径 $filter_dir = array('CVS', 'templates_c', 'log', 'img', ...

  9. iOS案例:读取指定目录下的文件列表

    // // main.m // 读取指定目录下的文件列表 // // Created by Apple on 15/11/24. // Copyright © 2015年 Apple. All rig ...

随机推荐

  1. 计算A+B及其结果的标准形式输出

    题目: 代码链接 解题思路: 首先,读懂题目,题目要求我们计算两个整型数a,b之和,这是简单的加法计算,与平常的题目一般无二.但是此题的不同在于要求我们输出的数必须是标准形式,题目也对标准形式做了相应 ...

  2. ubuntu12.04 安装 setuptools

    ubuntu 12.04 安装django时,提示缺少setuptools. 转载自: http://blog.csdn.net/xudongtiankong/article/details/8180 ...

  3. calc 的使用

    通常情况下,一个元素节点使用固定定位absolute和固定定位fixed,会遇到一个问题,如果设置100% ,此时你在对他设置padding,border,margin,它就会撑满 具体情况如下图:

  4. Chrome开发者工具不完全指南

    Chrome开发者工具不完全指南(一.基础功能篇) Chrome开发者工具不完全指南(二.进阶篇) Chrome开发者工具不完全指南:(三.性能篇) Chrome开发者工具不完全指南(四.性能进阶篇) ...

  5. Java 使用jaxp添加节点

    <?xml version="1.0" encoding="UTF-8"?> <person> <p1> <name& ...

  6. oracle pl sql 解锁表

    select   p.spid,a.serial#, c.object_name,b.session_id,b.oracle_username,b.os_user_name   from   v$pr ...

  7. windows Azure 域名绑定

    windows Azure 的虚拟机的ip是会变化的,比如你关机.所以绑定域名用A记录就不太可靠. 你新建虚拟机的同时,也会新建一个云服务,给你一个类似XX.cloudapp.net的二级域名. 这样 ...

  8. #pragma message的作用

    一般情况下,#pragma message( messagestring )是在编译期间,将一个文字串(messagestring)发送到标准输出窗口.典型的使用方法是在编译时报告和显示信息.下面的代 ...

  9. Leetcode: Random Pick Index

    Given an array of integers with possible duplicates, randomly output the index of a given target num ...

  10. linux [Fedora] 下的 "飞秋/飞鸽传书"

    官方网址: http://www.msec.it/blog/?page_id=11 http://software.opensuse.org/download.html?project=home:co ...