[英]how can I convert position (2nd, 3rd or 4th etc ) to index(00 for 1st position, 01 for 2nd etc) in 2D array in python numpy?
[英]How to Read the 2nd and 3rd line then Every Fifth Line After: 2nd, 3rd, 7th, 8th, 12th, 13th, etc
我正在嘗試從python中的文本文件讀取某些行。
我的文字檔:
Data Set
for this Event
d1: p, t, h = 9, 12, 30
d2: p, t, h = 12, 22, 11
Data Set
for this Event
d1: p, t, h = 9, 12, 30
d2: p, t, h = 12, 22, 11
etc.
我如何讀取第二行和第三行,然后是第七行,第八行,第十二行,第十三行,所以我只讀取包含數據的行,而跳過具有此事件的數據集的行。
這是我嘗試過的:
with open("d.txt") as f:
for line2 in f.read().split("\n")[2::5]:
print(line2)
for line3 in f.read().split("\n")[3::5]:
print(line3)
while line2:
line = []
line.append(line2)
print(line)
但這只給了我第二,第七,十二,十七等行。 我沒有得到第2、3、7、8、12、13等行,這是在做錯什么? 如果我寫line.append(line3)
相反,我得到以下錯誤:
Traceback (most recent call last):
File "write.py", line 9, in <module>
line.append(line3)
NameError: name 'line3' is not defined
任何指導將不勝感激!
編輯:在查看了答案和評論后,我現在嘗試將以下內容寫為我的代碼:
from itertools import tee, islice
with open("d.txt") as f:
f1 = islice(f, 2, None, 5)
f2 = islice(f ,3, None, 5)
for l1, l2 in f1, f2:
#print(f "{l1} --- {l2}")
pass
但是,我現在收到一個我不明白為什么會發生的錯誤:追溯(最近一次調用最近):文件“ write.py”,第6行,在f1,f2中用於l1,l2:ValueError:也要解開的許多價值觀
我現在仍然不是很清楚如何解決此代碼。 任何進一步的指導將不勝感激!
f.read()
耗盡要從文件中讀取的剩余字符的內部緩沖區。 這意味着,如果您連續兩次調用f.read()
,則第一個調用將起作用,而第二個調用將不起作用(由於第一次調用已耗盡文件,因此它將返回一個空字符串)。 您將必須使用seek()
方法將內部字符光標放回到文件的開頭。 或者,只需先閱讀所有行,然后再進行其余操作。
with open("d.txt") as f:
lines = f.readlines()
for line2 in lines[2::5]:
#...
for line3 in lines[3::5]:
#...
另一種選擇是使用正則表達式來匹配和保留僅遵循您要查找的模式的那些行。
正如其他人指出的那樣,您沒有獲得期望的答案的一個原因是,您第一次循環使用生成器之后就在使用它。
解決此問題的一種方法是,您可以利用以下事實:要讀取的行號只能取四個模10值,例如2、3、7、8、12、13、17、18, ...,然后使用enumerate
僅讀取所需的行。
valid = {2, 3, 7, 8}
with open("file.txt", "r") as fh:
for n, line in enumerate(fh.readlines()):
if n % 10 in valid:
print(line)
問題在於文件對象f
是一個iterator
,因此一旦遍歷它就將其耗盡。
您可以按照@ user10987432的說明使用f.seek(0)
返回開頭,也可以使用itertools.tee()
itertools.tee()
允許您從單個迭代器制作多個獨立的迭代器。
from itertools import tee, islice
with open('foo') as f:
f1, f2 = tee(f)
for l1, l2 in zip(islice(f1, 2, None, 5), islice(f2, 3, None, 5)):
print(f'{l1} --- {l2}')
將打印
d1: p, t, h = 9, 12, 30
--- d2: p, t, h = 12, 22, 11
d1: p, t, h = 9, 12, 30
--- d2: p, t, h = 12, 22, 11
\\n
不會自動刪除(至少在我的測試中),因此您需要自己處理
要選擇行[2、3、7、8、12、13、17、18 ...],您可以檢查其模5的索引是否等於2或3。
因此,給定行索引i
if (i % 5 == 2 or i % 5 == 3):
# append row to list of relevant rows
Python索引從0開始,因此您實際需要的是其索引模5等於1或2的行。
if (i % 5 == 1 or i % 5 ==2):
# append row
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.