我正在为工作开发一个小程序,为此我到处寻求帮助!
我想做的是让用户输入字符串进行搜索。该程序将在定义的目录中搜索多个 .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)
最佳答案
有很多更好的工具可以做到这一点(提到了 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)'
关于Python搜索字符串并打印它所在的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9271353/