在我的任务中,我必须在一个txt文件中写入两个指定单词之间的文本块(以这些单词开头的行)。输入文件如下所示:
SP_LINE
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
//
NON_SP_LINE
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
END_NON_LINE
SP_LINE
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
texttexttexttext
//
我必须在SP_LINE和' //'之间写入文件。 我试过这个:
import re
fr=open("various.multi").read()
gr=open("locus.txt",'w')
for m in re.finditer("SP_LINE",fr):
a=int(m.start())
for n in re.finditer("//", fr[a:]):
b=int(n.end())
gr.write(fr[a:b])
gr.close()
但它不起作用
答案 0 :(得分:1)
import re
gr=open("locus.txt",'w')
for line in open('data.txt'):
if re.match('SP_LINE|//', line):
continue
gr.write(line)
gr.close()
答案 1 :(得分:0)
试试这个:
import re
fr=open("various.multi").read()
gr=open("locus.txt",'w')
for m in re.finditer(r"\bSP_LINE\b",fr):
for n in re.finditer(r"//", fr[m.end():]):
gr.write(fr[m.start():m.end()+n.end()])
break
gr.close()
答案 2 :(得分:0)
这有用吗?
导入重新
fr=open("various.multi").read()
gr=open("locus.txt",'w')
for m in re.finditer("SP_LINE",fr):
a = int(m.start())
b = a + int(re.search("//", fr[a:]).start())
gr.write(fr[a:b])
gr.close()