2016-04-10 63 views
0

第一次使用文件和I/O的計時器。我通過測試人員運行我的代碼,測試人員通過我的代碼調用我正在處理的不同文件。因此,爲此,我在下面將文件表示爲「文件名」,並將該文件中的字符串表示爲「s」。我很確定我正在瀏覽代碼行並正確搜索字符串。這是我有這個:查找文件中的字符串

def locate(filename, s): 

    file= open(filename) 
    line= file.readlines() 
    for s in line: 
     if s in line: 
      return [line.count] 

我知道返回線路不正確。我將如何返回我正在查找的字符串作爲列表所在的行的編號?

回答

2

您可以使用enumerate跟蹤行號:

def locate(filename, s): 
    with open(filename) as f: 
     return [i for i, line in enumerate(f, 1) if s in line] 

如果搜索字符串能夠從第一和第三行中找到它會產生輸出如下:

[1, 3] 
+0

line到另一個變量除了您是不是要找返回'[我]'?我想你只是想'我'? – idjaw

+0

問題指出返回值應該是一個列表:「返回我正在查找的字符串所在的行的編號作爲列表」。當然,如果整數是首選,那麼它應該是你所說的'我'。 – niemmi

+0

啊!我認爲這是項目和索引在一起。 – idjaw

0

你可以使用enumerate

示例文本文件

hello hey s hi 
hola 
s 

代碼

def locate(filename, letter_to_find): 

    locations = [] 
    with open(filename, 'r') as f: 
     for line_num, line in enumerate(f): 
      for word in line.split(' '): 
       if letter_to_find in word: 
        locations.append(line_num) 
    return locations 

輸出

[0, 2] 

我們可以看到它顯示,上線0和2
注電腦字符串s從0開始

計數什麼在

  1. 會打開具有讀取權限的文件。

  2. 迭代每一行,enumerate,因爲它走了,並跟蹤line_num行號。

  3. 迭代該行中的每個單詞。

  4. 如果您傳遞給函數的letter_to_findword,它追加line_numlocations

  5. 回報locations

0

這些問題線

for s in line: 
    if s in line: 

你必須從s

def locate(filename, s): 

    file= open(filename) 
    line= file.readlines() 
    index = 0; 
    for l in line: 
     print l; 
     index = index + 1 
     if s in l: 
      return index 


print locate("/Temp/s.txt","s")