python实现搜索指定目录下文件及文件内搜索指定关键词的方法

yipeiwu_com5年前Python基础

本文实例讲述了python实现搜索指定目录下文件及文件内搜索指定关键词的方法。分享给大家供大家参考。具体实现方法如下:

#!/usr/bin/python -O
# -*- coding: UTF-8 -*-
"""
Sucht rekursiv in Dateiinhalten und listet die Fundstellen auf.
"""
__author__ = "Jens Diemer"
__license__ = """GNU General Public License v2 or above -
 http://www.opensource.org/licenses/gpl-license.php"""
__url__ = "http://www.jensdiemer.de"
__version__ = "0.1"
import os, time, fnmatch
class search:
  def __init__(self, path, search_string, file_filter):
    self.search_path = path
    self.search_string = search_string
    self.file_filter = file_filter
    print "Search '%s' in [%s]..." % (
      self.search_string, self.search_path
    )
    print "_" * 80
    time_begin = time.time()
    file_count = self.walk()
    print "_" * 80
    print "%s files searched in %0.2fsec." % (
      file_count, (time.time() - time_begin)
    )
  def walk(self):
    file_count = 0
    for root, dirlist, filelist in os.walk(self.search_path, followlinks=True):
      for filename in filelist:
        for file_filter in self.file_filter:
          if fnmatch.fnmatch(filename, file_filter):
            self.search_file(os.path.join(root, filename))
            file_count += 1
    return file_count
  def search_file(self, filepath):
    f = file(filepath, "r")
    content = f.read()
    f.close()
    if self.search_string in content:
      print filepath
      self.cutout_content(content)
  def cutout_content(self, content):
    current_pos = 0
    search_string_len = len(self.search_string)
    for i in xrange(max_cutouts):
      try:
        pos = content.index(self.search_string, current_pos)
      except ValueError:
        break
      content_window = content[ pos - content_extract : pos + content_extract ]
      print ">>>", content_window.encode("String_Escape")
      current_pos += pos + search_string_len
    print
if __name__ == "__main__":
  search_path = r"c:\texte"
  file_filter = ("*.py",) # fnmatch-Filter
  search_string = "history"
  content_extract = 35 # Gr��e des Ausschnittes der angezeigt wird
  max_cutouts = 20 # Max. Anzahl an Treffer, die Angezeigt werden sollen
  search(search_path, search_string, file_filter)

希望本文所述对大家的Python程序设计有所帮助。

相关文章

windows下Python安装、使用教程和Notepad++的使用教程

windows下Python安装、使用教程和Notepad++的使用教程

一、Python下载 1.进入Python官网:https://www.python.org/ 2.选择windows版本(Download > Windows) 3.点击下载P...

解决python3 urllib 链接中有中文的问题

环境python3,开发平台pycharm,使用urllib时,当url中存在中文时会出现以下错误: UnicodeEncodeError: 'ascii' codec can't...

Python实现识别手写数字大纲

写在前面 其实我之前写过一个简单的识别手写数字的程序,但是因为逻辑比较简单,而且要求比较严苛,是在50x50大小像素的白底图上手写黑色数字,并且给的训练材料也不够多,导致准确率只能五五开...

基于MSELoss()与CrossEntropyLoss()的区别详解

基于MSELoss()与CrossEntropyLoss()的区别详解

基于pytorch来讲 MSELoss()多用于回归问题,也可以用于one_hotted编码形式, CrossEntropyLoss()名字为交叉熵损失函数,不用于one_hotted编...

Python3实现发送QQ邮件功能(html)

本文为大家分享了Python3实现发送QQ邮件功能:html,供大家参考,具体内容如下 之前已经成功发送了qq邮件。下面贴出html格式的qq邮件 import smtplib f...