我有一個包含大約 50 個 14 行塊的檔案,每個塊都以我可以搜索的特定字串開頭。由于檔案在其他方面相當大,因此我將 enumerate 函式用作:
def search_and_return_a_block(l_no,file_path, string):
with open(file_path, 'r') as file:
for l_no, line in enumerate(file):
if string in line:
#append lines into a list of 14 lines
break
return list,l_no
現在,我只想要 50 個塊中的前 2 個塊,所以當我呼叫這個函式時,我希望從第一個塊的底部開始搜索,而不是從檔案的開頭開始搜索。該函式第一次回傳正確的行號。
但是,上面的 for 回圈總是從 0 開始并忽略我呼叫它的第一個引數 (l_no) 的值。這會導致它只列印第一個塊 2 次而不移動到下一個塊。
我還嘗試使用列舉函式的可選引數,但沒有成功。有沒有一種優雅的方式來做到這一點?
uj5u.com熱心網友回復:
我不完全確定你想要實作什么,而且我不是 Python 2 專家(不再),所以這可能不是你想要的:
from itertools import islice
def search_and_return_a_block(start, file_path, string):
block = []
no = start
with open(file_path, 'r') as file:
for no, line in enumerate(islice(file, start, None), start=start 1):
block.append(line.rstrip())
if string in line:
break
return block, no
如果你跑
start = 0
for _ in range(10):
block, start = search_and_return_a_block(start, 'file.txt', 'a')
print(block, start)
file.txt喜歡_
a
b
c
a
b
c
d
a
b
c
d
e
a
b
a
a
a
b
c
d
你會得到以下輸出:
['a'] 1
['b', 'c', 'a'] 4
['b', 'c', 'd', 'a'] 8
['b', 'c', 'd', 'e', 'a'] 13
['b', 'a'] 15
['a'] 16
['a'] 17
['b', 'c', 'd'] 20
[] 20
[] 20
但也許生成器函式更適合您的需求?您可以執行以下操作:
def search_and_return_a_block(start_block, file_path, string):
with open(file_path, 'r') as file:
blocks = 1
out = True if start_block == 1 else False
block = []
for line in file:
if out:
block.append(line.rstrip())
if string in line:
yield block
block = []
elif string in line:
blocks = 1
if blocks == start_block:
out = True
當您對同一檔案執行以下操作時
blocks = search_and_return_a_block(2, 'file.txt', 'a')
block_2 = next(blocks)
print(block_2)
block_3 = next(blocks)
print(block_3)
結果看起來像
['b', 'c', 'a']
['b', 'c', 'd', 'a']
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/464293.html
標籤:Python python-2.7
上一篇:在MacBookPro上更改asdf安裝的elasticsearch設定
下一篇:表視圖設計重疊
