2014-04-02 36 views
0

我必須編寫一個函數,它可以搜索短語的txt文件,然後打印包含該短語的每一行。如何從包含某個短語的文本文件打印每一行

def find_phrase(filename,phrase): 
    for line in open(filename): 
     if phrase in line: 
      print line, 

這是我的時刻,它只能打印第一個實例。

+0

這應該有效。你確定你有多個匹配(區分大小寫)的行嗎?另外:使用with語句,以便您完成後可以自動關閉文件。 – ramcdougal

+0

它適用於我一個簡單的示例文件。你能告訴我們你正在使用的文件嗎? – Germano

+0

它也適用於我。你可以發佈代碼的輸出示例嗎? – Tengis

回答

1

我試圖用一個示例腳本,它是這樣的

#sample.py 

import sys 
print "testing sample" 
sys.exit() 

當我運行腳本代碼,

find_phrase('sample.py','sys') 

它打印,

import sys 
sys.exit(). 

如果這不是你想要的輸出,請分享你正在使用的文件。

0

以下是pythonic方法。 with語句將安全地打開文件並在完成時處理關閉文件。您也可以使用「with」語句打開多個文件。 How to open a file using the open with statement

def print_found_lines(filename, phrase): 
    """Print the lines in the file that contains the given phrase.""" 
    with open(filename, "r") as file: 
     for line in file: 
      if phrase in line: 
       print(line.replace("\n", "")) 
    # end with (closes file automatically) 
# end print_found_lines 
+0

您應該用空格替換。爲了重現原來的發佈代碼。 – jimifiki

相關問題