python实现搜索文本文件内容脚本


Posted in Python onJune 22, 2018

本文介绍用python实现的搜索本地文本文件内容的小程序。从而学习Python I/O方面的知识。代码如下:

import os

#根据文件扩展名判断文件类型
def endWith(s,*endstring):
 array = map(s.endswith,endstring)
 if True in array:
  return True
 else:
  return False

#将全部已搜索到的关键字列表中的内容保存到result.log文件中
def writeResultLog(allExistsKeywords):
 #行分隔符
 ls = os.linesep
 #结果日志文件名
 logfilename = "result.log" #相对路径,文件在.py文件所在的目录中
 try:
  fobj = open(logfilename,'w')
 except IOError,e:
  print "*** file open error:",e
 else:
  fobj.writelines(['%s%s' % (keyword,ls) for keyword in allExistsKeywords])
  fobj.close() 


#搜索指定关键字是否在指定的文件中存在
def searchFilesContent(dirname):
 #从searchkeywords.txt文件中初始化待搜索关键字列表
 filename = "searchkeywords.txt" #相对路径,文件在.py文件所在的目录中
 #待搜索关键字列表
 allSearchKeywords=[]
 #遍历文件当前行已搜索到的关键字列表
 existsKeywordsThisLine=[]
 #全部已搜索到的关键字列表
 allExistsKeywords=[]

 try:
  fobj = open(filename,'r');
 except IOError,e:
  print "*** file open error:",e
 else:
  for eachLine in fobj:
   allSearchKeywords.append(eachLine.strip('\n')); #使用strip函数去除每行的换行符
  fobj.close();

 #从excludekeywords.txt文件中初始化要排除的搜索关键字列表
 filename = "excludekeywords.txt" #相对路径,文件在.py文件所在的目录中
 #要排除的搜索关键字列表
 allExcludedKeywords=[]
 try:
  fobj = open(filename,'r');
 except IOError,e:
  print "*** file open error:",e
 else:
  for eachLine in fobj:
   allExcludedKeywords.append(eachLine.strip('\n')); #使用strip函数去除每行的换行符
  fobj.close();

 #从全部已搜索到的关键字列表排除掉不用搜索的关键字
 for excluedkw in allExcludedKeywords:
  if(excluedkw in allSearchKeywords):
   allSearchKeywords.remove(excluedkw);


 #遍历打开所有要在其中搜索内容的文件,若待搜索关键字列表为空,则不再继续遍历
 for root,dirs,files in os.walk(dirname):
  for file in files:
   if endWith(file,'.java','.xml','.properties'): #只在扩展名为.java/.xml/.properties文件中搜索
    #打开文件
    filename = root + os.sep + file #绝对路径
    filename = filename.replace("\\","\\\\") #将路径中的单反斜杠替换为双反斜杠,因为单反斜杠可能会导致将路径中的内容进行转义了,replace函数中"\\"表示单反斜杠,"\\\\"表示双反斜杠
    try:
     fobj = open(filename,'r');
    except IOError,e:
     print "*** file open error:",e
    else:
     #遍历文件的每一行
     for fileLine in fobj:
      #判断当前行是否包含所有搜索关键字
      for keyword in allSearchKeywords:
       #若包含,并添加到该行已搜索到的关键字列表中
       if keyword.upper() in fileLine.upper(): #将搜索关键字和该行文本内容都转换为大写后再进行匹配
        existsKeywordsThisLine.append(keyword)

      #将这些搜索到的关键字添加到全部已搜索到的关键字列表中,并包含文件名信息
      for keyword in existsKeywordsThisLine:
       allExistsKeywords.append(keyword+"\t"+filename.replace("\\\\","\\"))

      #将这些搜索到的关键字从待搜索关键字列表中移除(后续将不再搜索该关键字)
      for keyword in existsKeywordsThisLine:
       allSearchKeywords.remove(keyword)

      #清空该行已搜索到的关键字列表内容
      existsKeywordsThisLine = []

      #若所有的关键字都搜索到了,则记录日志文件,并结束搜索工作
      if len(allSearchKeywords)==0:
       fobj.close();
       writeResultLog(allExistsKeywords)
       print "DONE!",
       return
     fobj.close();

 #全部文件遍历结束
 writeResultLog(allExistsKeywords)
 print "DONE!",



#仅当本python模块直接执行时,才执行如下语句,若被别的python模块引入,则不执行
if __name__ == '__main__':
 searchFilesContent(r"G:\ccsSmartPipe\SmartPipe\src\java")

1.笔者使用该程序对java项目中的源文件内容进行关键字的搜索。程序入参为该项目本地文件系统路径G:\ccsSmartPipe\SmartPipe\src\java。

2.在配置文件中searchkeywords.txt中输入要搜索的任意多个关键字

python实现搜索文本文件内容脚本

3.在配置文件中excludekeywords.txt中输入在searchkeywords.

python实现搜索文本文件内容脚本

4.程序执行完成后,即可在result.log日志文件中,查看搜索结果。即每个关键在哪些文件中存在。并给出每个文件的具体路径。

python实现搜索文本文件内容脚本

附件:源代码及配置文件

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python的Django中django-userena组件的简单使用教程
May 30 Python
十个Python程序员易犯的错误
Dec 15 Python
Python sqlite3事务处理方法实例分析
Jun 19 Python
python读取并定位excel数据坐标系详解
Jun 26 Python
Python中的类与类型示例详解
Jul 10 Python
django-rest-swagger的优化使用方法
Aug 29 Python
Python使用qrcode二维码库生成二维码方法详解
Feb 17 Python
Python进程间通信multiprocess代码实例
Mar 18 Python
tensorflow实现从.ckpt文件中读取任意变量
May 26 Python
Python列表如何更新值
May 27 Python
Python抓包并解析json爬虫的完整实例代码
Nov 03 Python
python绘图模块之利用turtle画图
Feb 12 Python
python实现textrank关键词提取
Jun 22 #Python
python实现自主查询实时天气
Jun 22 #Python
python实现定时提取实时日志程序
Jun 22 #Python
pandas 读取各种格式文件的方法
Jun 22 #Python
python使用turtle库绘制时钟
Mar 25 #Python
Python日期时间对象转换为字符串的实例
Jun 22 #Python
python pandas 对时间序列文件处理的实例
Jun 22 #Python
You might like
php中ftp_chdir与ftp_cdup函数用法
2014/11/18 PHP
PHP.vs.JAVA
2016/04/29 PHP
PHP实现适用于文件内容操作的分页类
2016/06/15 PHP
网页自动跳转代码收集
2009/09/27 Javascript
JQUERY操作JSON实例代码
2010/02/09 Javascript
用方法封装javascript的new操作符(一)
2010/12/25 Javascript
javascript操作符"!~"详解
2015/02/10 Javascript
实现前后端数据交互方法汇总
2015/04/07 Javascript
JS实现pasteHTML兼容ie,firefox,chrome的方法
2016/06/22 Javascript
nodejs中向HTTP响应传送进程的输出
2017/03/19 NodeJs
js实现延迟加载的几种方法
2017/04/24 Javascript
Node.js创建HTTP文件服务器的使用示例
2018/05/11 Javascript
js/jquery遍历对象和数组的方法分析【forEach,map与each方法】
2019/02/27 jQuery
vue.js自定义组件实现v-model双向数据绑定的示例代码
2020/01/08 Javascript
小程序跳转到的H5页面再跳转回跳小程序的方法
2020/03/06 Javascript
[45:15]Optic vs VP 2018国际邀请赛淘汰赛BO3 第一场 8.24
2018/08/25 DOTA
Python爬虫框架Scrapy安装使用步骤
2014/04/01 Python
python使用正则表达式替换匹配成功的组并输出替换的次数
2017/11/22 Python
深入浅析Python 中 is 语法带来的误解
2019/05/07 Python
Python人工智能之路 jieba gensim 最好别分家之最简单的相似度实现
2019/08/13 Python
python logging日志模块原理及操作解析
2019/10/12 Python
Python如何实现动态数组
2019/11/02 Python
Django配置文件代码说明
2019/12/04 Python
python上selenium的弹框操作实现
2020/07/13 Python
Python爬取微信小程序Charles实现过程图解
2020/09/29 Python
python Matplotlib基础--如何添加文本和标注
2021/01/26 Python
html Table 表头固定的实现
2019/01/22 HTML / CSS
日本食品网上商店:JaponShop.com
2017/11/28 全球购物
Beach Bunny Swimwear官网:设计师泳装和性感比基尼
2019/03/13 全球购物
Roxy俄罗斯官方网站:冲浪和滑雪板的一切
2020/06/20 全球购物
工作表扬信
2015/01/17 职场文书
2015年南京大屠杀纪念日活动总结
2015/03/24 职场文书
黄河绝恋观后感
2015/06/08 职场文书
2019请假条的基本格式及范文!
2019/07/05 职场文书
读《推着妈妈去旅行》有感1500字
2019/10/15 职场文书
详解CSS故障艺术
2021/05/25 HTML / CSS