【问题标题】:Finding string in a file [duplicate]在文件中查找字符串[重复]
【发布时间】:2016-07-31 04:56:40
【问题描述】:

第一次真正使用文件和 I/O。我正在通过测试仪运行我的代码,并且测试仪通过我的代码调用我正在使用的不同文件。因此,为此,我将文件表示为下面的“文件名”,并将我在该文件中查找的字符串表示为“s”。我很确定我正在浏览代码行并正确搜索字符串。这就是我所拥有的:

def locate(filename, s):

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

我知道退货线路不正确。我如何将我要查找的字符串所在的行号作为列表返回?

【问题讨论】:

    标签: python file io


    【解决方案1】:

    这些是问题所在

    for s in line:
        if s in line:
    

    您必须将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")
    

    【讨论】:

      【解决方案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]
      

      【讨论】:

      • 您是要返回[i]吗?我想你只是想要i
      • 问题指出返回值应该是一个列表:“返回我要查找的字符串作为列表所在的行号”。当然,如果首选整数,那么它应该是i,正如你所建议的那样。
      • 啊!我认为它是项目和索引一起。
      • 可能很难说,因为没有首选输出示例。行号和行内容显然是return [i, line]
      • 结论。不清楚:P
      【解决方案3】:

      您可以使用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. 遍历每一行,enumerateing 他们,并跟踪line_num 中的行号。

      3. 遍历行中的每个单词。

      4. 如果您传递给函数的letter_to_findword 中,它会将line_num 附加到locations

      5. 返回locations

      【讨论】:

        猜你喜欢
        • 2017-01-25
        • 2015-07-02
        • 2014-05-09
        • 1970-01-01
        • 1970-01-01
        • 2014-06-01
        • 2019-11-17
        • 2020-02-24
        • 1970-01-01
        相关资源
        最近更新 更多