在外部文本文件中查找字符串所在的行号

Find the line number a string is on in an external text file

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

我目前拥有的:

file = open('test.txt', 'r')
string = input("Enter string to search")
for string in file:
    print("") #print the line number
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")

你可以实现这个算法:

  • 初始化一个计数器
  • 逐行阅读
  • 如果行匹配目标,return当前计数
  • 增加计数
  • 如果没有 returning 就到达结尾,则该行不在文件中

例如:

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

如果 string 将准确匹配 line,我们可以在 one-line 中这样做:

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

嗯,以上那种作品,如果没有的话,print "no match" 也不会接受。为此,我们可以添加一点 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")

文本文件不同于程序(如字典和数组)中使用的内存,因为它是连续的。就像很久很久以前用于存储的旧磁带一样,如果不梳理所有先前的行(或以某种方式猜测确切的内存位置),就无法 grab/find 特定行。您最好的选择是创建一个 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