有更好的工具來做到這一點(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)'
聽起來像是grep的工作 – 2012-02-14 03:38:01