python 文件内搜索关键词并保存行号
来源:互联网 发布:围墙设计图纸含数据 编辑:程序博客网 时间:2024/05/22 15:23
main(DirPath , KeyWord ,OutputPath ,THREAD_NUM)
在DirPath文件夹内搜索KeyWord ,并将搜索结果(KeyWord 所在的行号)保存在OutputPath 中
采用多线程实现,线程数可以自己设置THREAD_NUM
#! /usr/bin/env python# endcoding:utf-8import os ,sys,timeimport threadingFileState = 0def GetAllFilesList(dirPath): fileList = [] for root, dirs, files in os.walk(dirPath): for fileObj in files: fileList.append(os.path.join(root,fileObj)) return fileListdef searchStrInFile(FilePath , KeyWord , OutputPath ): global FileState f = open(FilePath , "r") content = f.readlines() f.close() searchRecordList = [] for line,ele in enumerate(content): if KeyWord in ele: searchRecordList.append(line+1) # searchRecordList = [line+1 for line,ele in enumerate(content) if KeyWord in ele] if len(searchRecordList) :# print FilePath + " : " +str(len(searchRecordList)) # print the result while(FileState!=0): "do nothing" if FileState == 0: FileState = 1 fp_ouput = open( OutputPath,"a" ) fp_ouput.write("\n"+ FilePath + ": " + str(len(searchRecordList)) +"\n") for ele in searchRecordList : fp_ouput.write( " "+ str(ele) ) fp_ouput.close()# time.sleep(0.1) FileState = 0def main(DirPath , KeyWord ,OutputPath ,THREAD_NUM): FileList = GetAllFilesList(DirPath) fp_ouput = open( OutputPath,"w" ) fp_ouput.write("search " +KeyWord +" in " + dirPath + " " +time.strftime( '%Y-%m-%d %X', time.localtime() )) fp_ouput.close() for FilePath in FileList : add_flag = 0 while(add_flag == 0 ): if( threading.activeCount() - 1 < THREAD_NUM ): t = threading.Thread(target=searchStrInFile,args=(FilePath , KeyWord , OutputPath)) t.start() add_flag = 1if __name__=="__main__": DirPath = "D:\\ResultData\\0_100M" KeyWord = "computer" OutputPath = os.path.join(os.getcwd(),"search_result_muti.txt") THREAD_NUM = 5# begin = time() main(DirPath , KeyWord ,OutputPath ,THREAD_NUM)
1 0
- python 文件内搜索关键词并保存行号
- Python分割文件并分别保存
- Python保存json文件并格式化
- python dict转json并保存文件
- python 模拟百度搜索关键词
- MySql组内排序并展示行号
- python 读文件 和行号
- 在Python读取mat文件,并保存为pickle格式
- 三种Python下载url并保存文件的代码
- python 抓包保存为pcap文件并解析
- python 3.3 下载固定链接文件并保存
- python使用h5py读取mat文件数据,并保存图像
- 用python 读取txt文件并保存为array
- Python读取多个txt文件并进行保存
- Python获取网页源码并保存为文件Demo
- 使用python读取.txt文件并保存到Excel中
- 用python 读取txt文件并保存为array
- python实现:递归删除文件并保存删除记录
- Maven配置本地仓库(localRepository)位置
- OpenJudge4079:二叉搜索树
- 华年轻盏,淡写悲伤
- iOS动画效果、绘制图形
- 使用DECODE解决去字段中固定首字的匹配问题
- python 文件内搜索关键词并保存行号
- C++primer学习:面向对象程序设计(5):再探文本查询程序
- 配置Maven基础环境生成eclipse工程以及常用命令
- 0012闰年计算的C++实现
- CocoaPods安装和使用教程
- 二分图最大匹配的König定理及其证明
- Redis学习总结(2)——Java使用Redis
- 账号安全登录猜测
- AndroidTestCase来进行android 单元测试简介