阅读Python中的下一行

2024-05-20 13:44:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

这是我做的程序。我做这个只是为了解决这个具体的问题,所以在很多其他方面可能也不完美。

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)

因此文本文件将由术语和下面的定义组成。

例如:

Python
A programming language I am using

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

我试过不同的印刷品组合(行+1)等,但迄今为止运气不佳。


Tags: the字符串in程序for定义defline
3条回答

如果您的文件大小很小,那么您可以使用^{}读取该文件,它返回由\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.")

您的代码将每一行作为一个术语处理,在下面的代码中,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

在设置旗子之前,一定要有“如果找到了”。所以如果你找到你的搜索词,下一个迭代/行将被打印出来。

相关问题 更多 >