一直在日常工作中需要對(duì)代碼或者日志文件進(jìn)行某些關(guān)鍵字查詢,在linux下有便捷的shell命令,但是轉(zhuǎn)到window下就要安裝關(guān)鍵字查詢工具。最近有時(shí)間,干脆自己用python實(shí)現(xiàn)關(guān)鍵字查詢。主要功能有:
1-可以對(duì)單個(gè)文件進(jìn)行查詢
2-可以對(duì)指定路徑下的文件進(jìn)行查詢
3-查詢出關(guān)鍵字所在位置并統(tǒng)計(jì)次數(shù)
4-能夠象baidu那樣輸出關(guān)鍵字高亮顯示
工作原理:利用了python的正則表達(dá)式re.search(keyword,line)方法,此方法會(huì)返回關(guān)鍵字所在的行。然后對(duì)行進(jìn)行切片line.split(keyword),計(jì)算出關(guān)鍵字出現(xiàn)的次數(shù)。要輸出關(guān)鍵字高亮顯示,必修要能調(diào)用window控制臺(tái)字符顏色。這里我使用了WConio模塊。(http:///projects/wconio.html)
以下是具體的操作畫面,測(cè)試環(huán)境win7+python2.7.3
1)在指定的文件內(nèi)查找關(guān)鍵字

2)在指定的文件夾內(nèi)查找關(guān)鍵字

以下是主要代碼:
---------------------------------------------
#-*- 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
'+----------------------------------------------------------------------------+'
|