我有一个文件,其中每4行重复一次模式。我想看一下文件,如果第二行(在4行块内)长于2000个字符,我想将4行块写到外文件中。
我首先要说的是,我是生物学家而不是CS,所以我对编码还比较陌生。我试图使用枚举来计数我所在的行来完成我的任务,而且枚举也是可迭代的,因此我相信我可以在其上调用下一个函数。但是,当我运行下面的代码块时,我最终打印了该组中的所有四行,从理论上讲,我应该只打印第三行和第四行。但是,当我运行此代码时,最终将打印所有行。这是令人困惑的部分。
with open('file', 'r') as f:
for i, line in enumerate(f, 1):
if i % 4 == 1:
first_line = line
if i % 4 == 2:
if len(line.strip()) > 2000:
seq_line = line
third_line = next(f)
fourth_line = next(f)
print(third_line)
print(fourth_line)
else:
pass
即使我尝试一些简单的事情,例如:
with open('file', 'r') as f:
for i, line in enumerate(f, 1):
if i % 4 == 1:
first_line = line
if i % 4 == 2:
print(line)
print(next(f))
我最终得到了所有的答案,但我仍然不明白。
谢谢。
答案 0 :(得分:1)
我完全不会使用enumerate
或next
。
with open('file', 'r') as f:
# keep going until we exhaust the file
while True:
# read the next four lines of the file
line1 = f.readline()
line2 = f.readline()
line3 = f.readline()
line4 = f.readline()
# if any of the lines are completely blank, the file is exhausted
if not line1 or not line2 or not line3 or not line4:
break
# if line2 is long enough, print the block
if len(line2) > 2000:
print (line1)
print (line2)
print (line3)
print (line4)
答案 1 :(得分:1)
使用re
模块查找4行(regex101)的块:
import re
with open('file.txt', 'r') as f_in, \
open('file_out.txt', 'w') as f_out:
for g in re.finditer(r'([^\n]+(?:\n|\Z)){4}', f_in.read(), flags=re.DOTALL):
if len(g[0].splitlines()[1]) > 2000:
f_out.write(g[0])
答案 2 :(得分:0)
enumerate()
还返回一个迭代器。您可以将其分配给变量,然后使用next()
递增该变量,而不是递增文件迭代器。这样,索引i
就会正确递增。
with open('file', 'r') as f:
lines = enumerate(f, 1)
for i, line in lines:
if i % 4 == 1:
first_line = line
elif i % 4 == 2:
if len(line.strip()) > 2000:
seq_line = line
_, third_line = next(lines)
_, fourth_line = next(lines)
print(third_line)
print(fourth_line)
else:
pass
答案 3 :(得分:0)
如果文件不是足够大并且内存不是问题,您可以可以或者只是读入整个文档,然后使用for
来仅检查每第4行从第二行开始(记住索引从0开始,所以我们先检查#1,然后检查#5,#9等),而不必费心enumerate
,嵌套的if
语句,{ {1}}语句或模块化算术。
为确保每次都有完整的4行代码块,您可以遍历每4个完整代码块的最后一行(第3行,#7,#11等),然后仅进行检查在此之前的2行。找到匹配项时,写下所有4行。
next
with open(filename, 'r') as f:
lines = f.readlines()
with open(outputfile, "w") as g:
for line_num in range(3, len(lines), 4):
if len(lines[line_num - 2]) > 2000:
g.write(lines[line_num - 3])
g.write(lines[line_num - 2])
g.write(lines[line_num - 1])
g.write(lines[line_num])
的语法为range()
。因此,更具体地说,range(from, to, skip)
命令返回一个以range(3, len(lines), 4)
开头的所有整数的列表,然后一直到达等于文档中总行数的数字,但仅取每个第四个整数。因此,它是列表3
,依此类推,直到行号用完为止。