【问题标题】:Find the line number a string is on in an external text file在外部文本文件中查找字符串所在的行号
【发布时间】:2017-11-08 21:04:31
【问题描述】:

我正在尝试创建一个程序,它从用户输入的字符串中获取输入,并在文本文件中搜索该字符串并打印出行号。如果字符串不在文本文件中,它将打印出来。我该怎么做?另外我不确定即使是我到目前为止的 for 循环是否也适用于此,所以任何建议/帮助都会很棒:)。

到目前为止我所拥有的:

file = open('test.txt', 'r')
string = input("Enter string to search")
for string in file:
    print("") #print the line number

【问题讨论】:

  • string 是否与 line 完全匹配?

标签: python file text external


【解决方案1】:

你可以实现这个算法:

  • 初始化计数器
  • 逐行阅读
  • 如果该行与目标匹配,则返回当前计数
  • 增加计数
  • 如果到达末尾没有返回,则该行不在文件中

例如:

def find_line(path, target):
    with open(path) as fh:
        count = 1
        for line in fh:
            if line.strip() == target:
                return count
            count += 1

    return 0

【讨论】:

    【解决方案2】:

    文本文件与程序(例如字典和数组)中使用的内存的不同之处在于它是顺序的。就像很久很久以前用于存储的旧磁带一样,如果不梳理所有先前的行(或以某种方式猜测确切的内存位置),就无法抓取/找到特定的行。您最好的选择是创建一个 for 循环,该循环遍历每一行,直到找到它正在寻找的那一行,然后返回该点之前遍历的行数。

    file = open('test.txt', 'r')
    string = input("Enter string to search")
    lineCount = 0
    for line in file:
        lineCount += 1
        if string == line.rstrip(): # remove trailing newline
            print(lineCount)
            break
    

    【讨论】:

      【解决方案3】:
      filepath = 'test.txt'
      substring = "aaa"
      with open(filepath) as fp:  
         line = fp.readline()
         cnt = 1
         flag = False
         while line:
             if substring in line:
                  print("string found in line {}".format(cnt))
                  flag = True
                  break
             line = fp.readline()
             cnt += 1
         if not flag:
             print("string not found in file")
      

      【讨论】:

        【解决方案4】:

        如果stringline 完全匹配,我们可以在one-line 中执行此操作:

        print(open('test.txt').read().split("\n").index(input("Enter string to search")))
        

        如果没有,上述类型的作品接受它不会print“不匹配”。为此,我们可以添加一点try

        try:
            print(open('test.txt').read().split("\n").index(input("Enter string to search")))
        except ValueError:
            print("no match")
        

        否则,如果string 只是在某处lines 之一,我们可以这样做:

        string = input("Enter string to search")
        for i, l in enumerate(open('test.txt').read().split("\n")):
            if string in l:
                print("Line number", i)
                break
        else:
            print("no match")
        

        【讨论】:

          猜你喜欢
          • 2015-07-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-30
          • 2013-04-18
          • 1970-01-01
          相关资源
          最近更新 更多