簡體   English   中英

閱讀Python中的下一行

[英]Read next line in 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 ,程序應輸出定義。

我嘗試了不同的打印組合(行+ 1)等但到目前為止沒有運氣。

你的代碼作為一個術語處理每一行,在下面的代碼中f是一個迭代器,所以你可以使用next將它移動到下一個元素:

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

如果你的文件大小很小,那么你可以通過使用readlines()返回一個字符串列表來讀取文件,每個字符串由\\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.")

你可以嘗試快速和臟標志。

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

在設置標志之前獲得“if 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM