一直在日常工作中需要对代码或者日志文件进行某些关键字查询,在linux下有便捷的shell命令,但是转到window下就要安装关键字查询工具。最近有时间,干脆自己用python实现关键字查询。主要功能有:
1-可以对单个文件进行查询
2-可以对指定路径下的文件进行查询
3-查询出关键字所在位置并统计次数
4-能够象baidu那样输出关键字高亮显示
工作原理:利用了python的正则表达式re.search(keyword,line)方法,此方法会返回关键字所在的行。然后对行进行切片line.split(keyword),计算出关键字出现的次数。要输出关键字高亮显示,必修要能调用window控制台字符颜色。这里我使用了WConio模块。(http:///projects/wconio.html)
以下是具体的操作画面,测试环境win7+python2.7.3
1)在指定的文件内查找关键字

2)在指定的文件夹内查找关键字

以下是主要代码:
---------------------------------------------
#-*- encoding: utf-8 -*-
#author : rayment
#CreateDate : 2012-07-04
#version 1.0
import re
import sys
import os
#http:///projects/wconio.html
import WConio
import countTime
def getParameters():
'''
get
parameters from console command
'''
ret =
[]
if
len(sys.argv) < 3 or len(sys.argv) >
4:
print 'Please input correct parameter, for example:'
print 'No1. python search.py keyword filepath'
print 'No2. python search.py keyword folderpath txt'
else:
for i in range(1, len(sys.argv)):
#print i, sys.argv[i]
ret.append(sys.argv[i])
print
'+============================================================================+'
print ' Keyword = %s'%sys.argv[1]
return
ret
def isFileExists(strfile):
'''
check the
file whether exists
'''
return
os.path.isfile(strfile)
def isDirExists(strdir):
'''
check the
dir whether exists
'''
return
os.path.exists(strdir)
def getFileList(strdir, filetype):
'''
get a type
of file list in a folder
'''
flist =
[]
for root,
dirs, fileNames in os.walk(strdir):
if fileNames:
for filename in fileNames:
if (filetype == filename.split('.')[1]):
filepath = os.path.join(root, filename)
flist.append(filepath)
return
flist
def Search(keyword, filename):
'''
search the
keyword in a assign file
'''
if(isFileExists(filename) == False):
print 'Input filepath is wrong,please check again!'
sys.exit()
print
'+----------------------------------------------------------------------------+'
print
' Filename = %s'%filename
print
'+----------------------------------------------------------------------------+'
|