2012-02-14 93 views
1

我正在研究一個小型工作計劃,並且我已經到處尋找幫助!Python搜索字符串並打印它所在的文件

我想要做的是讓用戶放入字符串進行搜索。程序將搜索定義目錄中的多個.txt文件,然後輸出結果,或使用默認文本編輯器打開.txt文件。

有人可以請指出我在這個搜索功能的正確方向嗎?

在此先感謝!

編輯: 這是我迄今爲止。我不能使用grep,因爲這個程序將在Windows和OSX上運行。我還沒有在Windows上測試,但在OSX上我的結果是拒絕訪問。下面

import os 
    import subprocess 

    text = str(raw_input("Enter the text you want to search for: ")) 

    thedir = './f' 
    for file in os.listdir(thedir): 
     document = os.path.join(thedir, file) 
     for line in open(document): 
      if text in line: 
       subpocess.call(document, shell=True) 
+2

聽起來像是grep的工作 – 2012-02-14 03:38:01

回答

2

的提示,你的答案:)

您可以使用os.walk遍歷所有文件在指定的目錄結構,搜索的字符串的文件中,使用subprocess模塊打開的文件需要編輯...

0
import os 
import subprocess 

text = str(raw_input("Enter the text you want to search for: ")) 

thedir = 'C:\\your\\path\\here\\' 
for file in os.listdir(thedir): 
    filepath = thedir + file 
    for line in open(filepath): 
     if text in line: 
      subprocess.call(filepath, shell=True) 
      break 
+0

我修改了一點,以適應我的runn代碼,它似乎工作除了無法運行子進程。我相信這是由於我在OSX上運行,如果我沒有記錯,必須導入某些東西才能與OSX一起使用,但我不記得它是什麼。 – 2012-02-14 04:22:54

4

有更好的工具來做到這一點(grep所提到的,它可能是最好的方式)。

現在,如果你想要一個Python的解決方案(這將運行速度非常慢),你可以從這裏開始:

import os 

def find(word): 
    def _find(path): 
     with open(path, "rb") as fp: 
      for n, line in enumerate(fp): 
       if word in line: 
        yield n+1, line 
    return _find 

def search(word, start): 
    finder = find(word) 
    for root, dirs, files in os.walk(start): 
     for f in files: 
      path = os.path.join(root, f) 
      for line_number, line in finder(path): 
       yield path, line_number, line.strip() 

if __name__ == "__main__": 
    import sys 
    if not len(sys.argv) == 3: 
     print("usage: word directory") 
     sys.exit(1) 
    word = sys.argv[1] 
    start = sys.argv[2] 
    for path, line_number, line in search(word, start): 
     print ("{0} matches in line {1}: '{2}'".format(path, line_number, line)) 

請藉此與一粒鹽:它不會使用正則表達式,或一點都不聰明。例如,如果您嘗試搜索「hola」,它將匹配「nicholas」,但不匹配「Hola」(在後一種情況下,您可以添加一個line.lower()方法。

一開始向您展示一個可能的方式開始。然而,請請使用grep

乾杯

採樣運行(我叫這個腳本「pygrep.py」; $是命令提示符)。

$python pygrep.py finder .       
./pygrep.py matches in line 12: 'finder = find(word)' 
./pygrep.py matches in line 16: 'for line_number, line in finder(path):' 
./pygrep.py~ matches in line 11: 'finder = find(word)' 
相關問題