python實現搜尋指定目錄下檔案及檔案內搜尋指定關鍵詞的方法

來源:互聯網
上載者:User

  本文執行個體講述了python實現搜尋指定目錄下檔案及檔案內搜尋指定關鍵詞的方法。分享給大家供大家參考。具體實現方法如下:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 #!/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程式設計有所協助。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.