阅读Python中的下一行

阅读Python中的下一行,python,Python,我试图找出如何在文本文件中搜索字符串,如果找到该字符串,则输出下一行 我在这里看过一些类似的问题,但没有从他们那里得到任何帮助 这是我制作的节目。我做它仅仅是为了解决这个特定的问题,所以它在许多其他方面也可能不完美 def searcher(): print("Please enter the term you would like the definition for") find = input() with open ('glossaryterms.txt', 'r

我试图找出如何在文本文件中搜索字符串,如果找到该字符串,则输出下一行

我在这里看过一些类似的问题,但没有从他们那里得到任何帮助

这是我制作的节目。我做它仅仅是为了解决这个特定的问题,所以它在许多其他方面也可能不完美

def searcher():
    print("Please enter the term you would like the definition for")
    find = input()
    with open ('glossaryterms.txt', 'r') as file:
        for line in file:
            if find in line:
                print(line)
因此,文本文件将由以下术语和定义组成

例如:

def searcher():
    last_line = ""
    print("Please enter the term you would like the definition for")
    find = input()
    with open ('glossaryterms.txt', 'r') as file:
        for line in file:
            if find in last_line:
                print(line)
            last_line = line
Python
我正在使用的一种编程语言

如果用户搜索术语
Python
,程序应输出定义


我尝试了不同的打印组合(第+1行)等,但到目前为止没有成功。

如果您的文件大小很小,那么您可以使用该文件读取该文件,该文件返回一个字符串列表,每个字符串由
\n
字符分隔,然后找到所选单词的索引,并在给定列表的+1位置打印该项目

这可以通过以下方式实现:

def searcher():
    print("Please enter the term you would like the definition for")
    find = input()

    with open("glossaryterms.txt", "r") as f:       
        words = list(map(str.strip, f.readlines()))
        try: 
            print(words[words.index(find) + 1])
        except:
            print("Sorry the word is not found.")

在我看来,最简单的方法是缓存最后一行。这意味着在任何迭代中,您都会有上一行,并且您会检查它——保持循环相对相似

例如:

def searcher():
    last_line = ""
    print("Please enter the term you would like the definition for")
    find = input()
    with open ('glossaryterms.txt', 'r') as file:
        for line in file:
            if find in last_line:
                print(line)
            last_line = line

您的代码将每一行作为一个术语处理,在下面的代码中,f是一个迭代器,因此您可以使用next将其移动到下一个元素:

with open('test.txt') as f:
    for line in f:
        nextLine = next(f)
        if 'A' == line.strip():
            print nextLine

你可以用旗子快速而肮脏地试一试

with open ('glossaryterms.txt', 'r') as file:
  for line in file:
    if found:
        print (line)
        found = False
    if find in line:
        found = True

在设置标志之前,重要的是要有“如果找到:”的标记。因此,如果您找到搜索词,下一次迭代/行将被打印。

最好举个例子:)谢谢。你能在代码中给我一个这样的例子吗?因为我无法将你在代码中所说的翻译成工作行?@user1480135:Check
file.readlines()
读取文件的所有行,并将这些行放入列表。感谢@KevinGuan提供的链接:)这是值得检查的。不确定您的示例是否符合原始规范(即,find字符串必须在行中,而不是行中,例如在示例中搜索Py),但我想修复起来相对简单!最好使用
next()
函数,而不是调用
迭代器.next()
方法。如果搜索字符串不在两的倍数上,则不起作用-每一个奇数行都被跳过。将下一行移到print语句中可以解决这一问题,但会产生另一个问题,即如果在该行中再次找到下一行,则下一行将不会被删除printed@meiamsome:“所以文本文件将由术语组成,然后是它下面的定义。”@PawełKordowski啊,是的,可能很好吧!哈哈,谢谢。我还不知道为什么,但我会尝试拆除它来帮助我理解。再次感谢理论上我会认为这是可行的,但由于某些原因,它只是在搜索词被删除后没有任何作用entered@user1480135对我来说效果很好,如果您使用的是Python2,它应该是原始输入,也许这就是问题所在?