• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

python搜索指定目录的文件,并进行文件内搜索指定的关键词

PHP 水墨上仙 3040次浏览 0个评论

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搜索指定目录的文件,并进行文件内搜索指定的关键词
喜欢 (0)

您必须 登录 才能发表评论!

加载中……