2017-03-09 16 views
0

我有一個文件,我正在搜索並將結果打印到文件中。我想知道是否可以修改下面的代碼來讀取多個搜索條件,即打印任何具有「test」或「hello」(用戶將指定)的行,但是Python會爲每個搜索項創建一個新的輸出文件?多個搜索條件和輸出文件

即Ofile1將舉行包括「測試」 Ofile2將舉行包括「你好」等

f = open('file3.txt') #input file 

term = raw_input("What would you like to search for?") #takes an input to be searched 

for line in f: 
    if term in line: 
     print (line) #print line of matched term 

f.close() #close file 

這是可以做到的所有行的所有行?

+0

在詢問之前,您是否在尋找一些信息?這是非常簡單的問題。 –

+0

不要吝嗇,但我不會問我是否找到它。 – here2learn

回答

1

基於的@new用戶代碼(改善一些錯誤),你可以做這樣的事情:

terms = raw_input("What would you like to search for?") 
terms = terms.split(" ") 
for term in terms: 
    f = open('text.txt') 
    filename = '{}_output.txt'.format(term) 
    o = open(filename, 'w') 
    for line in f: 
     if term in line: 
      o.write(line) 
    o.close() 
    f.close() 

也許你可以認爲這是更好地打開文件一次,每行檢查一些術語。根據術語數量的不同,如果您想要使用真正的大文件來檢查執行時間並瞭解更多信息,那麼效率會更高或更低。

+0

非常感謝。出於興趣,爲什麼在搜索「.jpg」時找不到任何內容,但會找到所有「jpg」文件?修改後的代碼忽略該情況 – here2learn

0

用空格分隔你的術語。然後使用for循環遍歷所有的術語。

例如:

terms = term.split(" ") 
for t in terms: 
    filename = t +"_output.txt" 
    o = open(filename,'w') 
    for line in f: 
     if t in line: 
      o.write(line) #print line of matched term 
    o.close() 
+0

此示例代碼失敗,因爲之後使用't'的名稱就像'term'一樣。如果用戶輸入多於一個單詞,則代碼僅保存第一個,第二個(等等)的文件,而不是因爲文件內的指針位於最後一個文件中,並且當您檢查第二個文件時不移動到開始文件(等等)一詞。您可以在代碼末尾使用[tell method](https://docs.python.org/2/tutorial/inputoutput.html)來檢查這一點。 而且您還需要關閉所有打開的文件。 這只是一個建議,我們在這裏學習。 –