2016-04-10 65 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")