2012-02-14 92 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)' 
相关问题