Python。在 1 行加入特定行

标签 python lines string-parsing reorganize

假设我有这个文件:

1
17:02,111
Problem report related to
router

2
17:05,223
Restarting the systems

3
18:02,444
Must erase hard disk
now due to compromised data

我想要这个输出:

1
17:02,111
Problem report related to router

2
17:05,223
Restarting the systems

3
18:02,444
Must erase hard disk now due to compromised data

一直在 bash 中尝试并找到了一种接近的解决方案,但我不知道如何在 Python 上执行此操作。

提前致谢

最佳答案

如果你想删除 extea 线:

为了这个目的,如果该行后面没有空新行,或者该行之前应该有一个与以下正则表达式 ^\d{2} 匹配的行,您可以为每个类似的条件检查 2 个条件:\d{2},\d{3}\s$.

因此,为了在每次迭代中访问下一行,您可以使用 itertools.tee 从主文件对象创建一个名为 temp 的文件对象。并在其上应用 next 函数。并使用 re.match 来匹配正则表达式。

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

结果:

1
17:02,111
Problem report related to

2
17:05,223
Restarting the systems

3
18:02,444
Must erase hard disk

如果你想将其余部分连接到第三行:

如果您想将第三行之后的其余行连接到第三行,您可以使用以下正则表达式来查找后跟 \n\n 或文件末尾 ( $) :

r"(.*?)(?=\n\n|$)"

然后根据日期格式的行拆分块并将部分写入输出文件,但请注意您需要用空格替换第三部分中的新行:

ex.txt:

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

演示:

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',' '))

结果:

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

注意:

在这个答案中,splitter 函数返回一个生成器,当您处理大文件并拒绝在内存中存储不可用的行时,该生成器非常高效。

关于Python。在 1 行加入特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30934765/

相关文章:

regex - 如何在 Perl 标量中只保留前五行?

r - xtable 中的水平虚线或点线

bash - Linux egrep 并加入

php - JSON 解析 : from PHP5 ( which attacks a database: mySQL ) ios5 iphone

python - 在字典中迭代..(双重迭代)python

python - 类型错误 : 'DiGraph' object does not support item assignment

python - pyQT 和 MySQL 或 MSSQL 连接

python - Django 忽略来自第三方模块的翻译字符串

javascript - 用逗号 (,) 分隔并检查是否有任何值 = "something"

javascript - 不使用 JSON.parse 解析字符串