2014-10-08 60 views
0

我在一个目录中有很多文本文件。然后我会询问用户的关键字。如果用户输入例如:'hello'
然后,它必须搜索文本文件中存在的所有目录的整个文本文件,然后搜索并返回文本文件的行,该文本文件具有单词hello的高优先级。python使用搜索引擎在文本文件中查找文本

如:

input: helloworld 

输出:

​​

给我如何处理这类问题的一些想法!

+1

委托给'grep',比在Python中做的任何事情都快。 – Amadan 2014-10-08 02:41:51

+1

根据你有多少文件,它们有多大,等等,你可能想看看Whoosh,一个用纯Python编写的全文索引软件包 – duhaime 2014-10-08 02:41:53

+0

@Amadan你能解释一下还是提供一些链接? – 2014-10-08 02:42:53

回答

1
import subprocess 
output = subprocess.check_output(["/usr/bin/env", "grep", "-nHr", "hello", "."]) 
matches = (line.split(":", 2) for line in output.split("\n") if line != "") 
for [file, line, text] in matches: 
    .... 

这会在当前目录或下面找到所有关于“hello”的提及。 man grep有关选项的详细信息。请注意,您需要引用任何特殊字符;如果你正在寻找简单的单词,这不是必要的,但如果你正在处理用户输入,你需要关心它。

3

使用glob作为替代,您可以筛选特定文件名,扩展名或目录中的所有文件。

>>> from glob import glob 
>>> key = 'hello' 
>>> for file in glob("e:\data\*.txt"): 
    with open(file,'r') as f: 
     line_no = 0 
     for lines in f: 
      line_no+=1 
      if key.lower() in lines.lower(): 
       print "Found in " + file + "(" + str(line_no) + "): " + lines.rstrip() 

Found in e:\data\data1.txt(1): Hello how are you 
Found in e:\data\data2.txt(4): Searching for hello 
Found in e:\data\data2.txt(6): 3 hello