Python在大文本文件中按条件随机插入行
我有一个超过30000行的文本文件,需要用Python来修改。我的目标是:
文件中有一个特定的关键词keyword1,后面跟着一个设备名称。我需要在所有行中找到这个keyword1,并提取出所有的设备名称,然后把它们存储在一个列表中,以便后续使用。
我通过使用正则表达式实现了这一点。
一旦我得到了设备名称的列表,我需要在文件中一些特定的位置插入一个新行,内容是“固定格式 + 设备名称”,这个位置是在keyword2之后。
这就是我遇到问题的地方。
最开始我使用了简单的计数方法。我在文件中使用
pattern.search(line)
来查找,一旦找到keyword1,我就通过计算i + 5来确定插入位置,其中i是找到keyword1的行的索引。然而,事实证明,文件中的行顺序是很重要的,所以我需要在keyword2所在的行之后插入新行。更麻烦的是,keyword2在文件中到处都有。只有在keyword1之后的7行内的keyword2才需要考虑。
举个例子:
This is a random line with KEYWORD2 <--- this keyword2 is not considered
This is a random line
This is a random line
This is a random line, KEYBOARD1 "DEVICE NAME" <--- id keyword1 and record DEVICE
This is a random line
This is a random line
This is a random line
This is a random line
This is a random line with KEYWORD2 <--- this keyword2 is considered
任何建议都很受欢迎。提前谢谢!
2 个回答
0
你可以用一个正则表达式来解决这个问题。比如说:
In [13]: p = re.compile('(.*kw1.*\n.*\n.*kw2.*$)', re.MULTILINE)
In [14]: p.sub(r'\1\n', 'bla kw1\nbla \n bla kw2 blub')
Out[14]: 'bla kw1\nbla \n bla kw2 blub\n'
你需要把这个表达式扩展到七行,并添加你相关的关键词。
1
我觉得你可以用这样的方式来处理这个问题:
with open('input.txt') as fhi, open('output.txt', 'w') as fho:
for line in fhi:
if not pattern.search(line):
# if there is no match write the line to the output file and proceed.
fho.write(line)
continue
# if we get this far we found a match. Scan up to seven lines.
for i in range(7):
toCheck = next(fhi)
if not pattern2.search(toCheck):
# if we don't find the 2nd keyword write the line, continue the sub-loop.
fho.write(toCheck)
continue
# if we get this far we found the second pattern. Add our newline.
fho.write(toCheck)
fho.write('\r\n')
这里使用的是在2.7版本中引入的多文件语法。如果你用的是更早的版本,就需要把with语句嵌套起来,或者手动管理文件句柄。