簡體   English   中英

在python中遍歷文件時更改索引

[英]change index while looping through file in python

假設我必須讀取一個文件(很大,大約20.000行)。 我必須遍歷所有行並尋找關鍵字,例如STACKOVERFLOW 一旦找到關鍵字,我知道我將不得不處理接下來的10行。

目前我正在做的像:

with open(filepath) as f:
    for line_idx, line in enumerate(f):
        if re.match(my_keyword, line):
            # do something here from line_idx to line_idx + 9
            # can i jump directly to line_idx + 10 ???

找到關鍵字后,是否有一種方法可以跳過接下來的10行的處理(循環+搜索),並繼續循環並在例如line_index + 10處繼續搜索?

謝謝!

更新

我想補充一點,就是我不需要將文件臨時保存到列表中。 使用這種方法,我已經有了解決方案。

您可以只使用普通的for循環,而不是for-each循環:

with open(filepath) as f:
    lines = f.readlines()
    for i in range(len(lines)):
        if re.match(my_keyword, lines[i]):
            # do something
            i += 10

但是,它將使用比當前更多的內存,因為您一次將整個文件讀入內存。 要記住的事情。

另外,如果將整個文件讀入內存是一個問題,則可以一起破解一些東西:

with open(filepath) as f:
    skip = 0
    for line in f:
        if skip <= 0:
            if re.match(my_keyword, line):
                skip = 10
        else:
            skip -= 1
            print(line) # The next ten lines after a match can be processed here

//可能的解決方案可以是

f = open(filepath,"r")
lines = f.readlines()
count = -1
req_lines = []
for line in lines:
    count += 1
    if re.match(my_keyword, line):
        for i in range(10):
            count += 1
            req_lines.append(lines[count])

//現在,您需要的行位於名為“ req_lines”的變量中,您可以對它們執行任何操作。

暫無
暫無

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

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