2014-10-08 37 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