<h2>如果要删除extea行:</h2>
<p>为此,如果行后面没有空行,或者行前面应该有一行与后面的regex <code>^\d{2}:\d{2},\d{3}\s$</code>匹配的行,则可以为每个like检查2个条件。在</p>
<p>因此,为了在每次迭代中访问下一行,您可以使用<a href="https://docs.python.org/3/library/itertools.html#itertools.tee" rel="nofollow">^{<cd3>}</a>从主文件对象创建一个名为<code>temp</code>的文件对象,并对其应用<code>next</code>函数。并使用<code>re.match</code>匹配正则表达式。在</p>
<pre><code>from itertools import tee
import re
with open('ex.txt') as f,open('new.txt','w') as out:
temp,f=tee(f)
next(temp)
try:
for line in f:
if next(temp) !='\n' or re.match(r'^\d{2}:\d{2},\d{3}\s$',pre):
out.write(line)
pre=line
except :
pass
</code></pre>
<p>结果:</p>
^{pr2}$
<hr/>
<h2>如果要将其余部分连接到第三行:</h2>
<p>如果您想将第三行后面的其余行连接到第三行,可以使用下面的正则表达式来查找后跟<code>\n\n</code>或文件结尾(<code>$</code>)的所有块:</p>
<pre><code>r"(.*?)(?=\n\n|$)"
</code></pre>
<p>然后根据日期格式中的行拆分块,并将部分写入输出文件,但请注意,您需要将第三部分中的新行替换为空格:</p>
<p>在附件公司名称:</p>
<pre><code>1
17:02,111
Problem report related to
router
another line
2
17:05,223
Restarting the systems
3
18:02,444
Must erase hard disk
now due to compromised data
line 5
line 6
line 7
</code></pre>
<p>演示:</p>
<pre><code>def splitter(s):
for x in re.finditer(r"(.*?)(?=\n\n|$)", s,re.DOTALL):
g=x.group(0)
if g:
yield g
import re
with open('ex.txt') as f,open('new.txt','w') as out:
for block in splitter(f.read()):
first,second,third= re.split(r'(\d{2}:\d{2},\d{3}\n)',block)
out.write(first+second+third.replace('\n',' '))
</code></pre>
<p>结果:</p>
<pre><code>1
17:02,111
Problem report related to router another line
2
17:05,223
Restarting the systems
3
18:02,444
Must erase hard disk now due to compromised data line 5 line 6 line 7
</code></pre>
<h2><em>注:</h2>
<p>在这个答案中,<code>splitter</code>函数返回一个生成器,当您处理巨大的文件并拒绝在内存中存储不可用的行时,该生成器非常有效。在</p>