我有此文本,我想阅读它的特定内容:
fist one:
=======
1
b
2
c
3
next one:
=========
4
5
d
6
7
third one:
=======
8
9
e
10
fourth one:
=======
11
12
d
13
我想只读取每个块的编号并将它们写入一个文件中。输出应为:
1
b
2
c
3
8
9
e
10
很抱歉,因为上下文不同,我无法在此处编写代码。我尝试了for循环,正则表达式和readline(s)以及Startwith(“第一拳:”),但是无法跳过“ =====”,我想检查块的名称是否匹配,然后仅取数字。
many thanks for your help
读取所有行并进行处理-如果某行在已知块名列表中,则设置一些布尔值。跳过下一行====行并捕获此行之后的所有行,直到任一行:
可能看起来像这样:
# write data
with open("f.txt","w") as f:
f.write("""fist one:\n=======\n1\n2\n3\n\nnext one:\n=========\n4\n5\n6\n\n7\n\n
third one:\n=======\n8\n9\n10\n\n\nfourth one:\n=======\n11\n12\n13""")
# list of blocks to be read
names = ["next one:", "fourth one:"]
# file processing
with open("f.txt") as r, open("r.txt", "w") as w:
capture = False
startingline = False
for line in r:
l = line.strip() # remove \n for l
if not l:
continue # skip empty lines
if l in names: # check if this is a block we watch out for
startingline = True # this will "eat" the ===== line that follows
capture = True # this allows capturing
continue
if startingline: # "eat" ========
if set(l) == set("="):
startingline = False
continue
if capture: # if we capture we keep all isdigit lines and stop
if l.isdigit():
w.write(line)
elif set(l) == set("="): # if we encounter another ==== line
capture = False
with open("r.txt") as f:
print(f.read())
输出:
4 # next one
5
6
7
11 # fourth one
12
13
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句