在 python 中的匹配前添加文本 2 行

Add text 2 lines before match in python

我正在尝试查找 "AAXX" 并在上面两行中添加单词 "Hello":

Input:
111
222
AAXX
333
444
AAXX
555
666
AAXX

Output: 
Hello 
111
222
AAXX
Hello
333 
444
AAXX
Hello
555
666
AAXX

我设法使用下面的代码在第一行 "AAXX" 之前的两行中只插入了一个 "Hello",但是我无法让它遍历文件并对所有 "AAXX" 场比赛。

import os

with open(os.path.expanduser("~/Desktop/test.txt"), "r+") as f:
    a = [x.rstrip() for x in f]
    for i, item in enumerate(a):
        if item.startswith("AAXX"):
            a.insert(i-2,"Hello")
            break
        index += 1
    # Go to start of file and clear it
    f.seek(0)
    f.truncate()
    # Write each line back
    for line in a:
        f.write(line + "\n")

到目前为止,我得到:

Hello
111
222
AAXX
333
444
AAXX
555
666
AAXX
def p(a):
    r = []
    for i, item in enumerate(a):
        if item.startswith("AAXX"):
            r.append(i)
    for i in reversed(r):
        a.insert(i-2,"HELLO")
    return(a)

您可以根据需要处理 inputs/outputs。您需要修复前两项中出现 "AAXX" 的情况,因为您尚未定义您想要的行为。关键问题是在迭代列表时修改列表是不好的做法,特别是后面的索引可能会关闭,因为您已经插入了较早的 "HELLO"s。一种可能的解决方案是跟踪所有插入索引,然后以 反向 顺序执行插入,因为在列表中稍后插入不会影响较早的索引。

你可以尝试以下方法吗:

with open('test.txt', 'r') as infile:
    data = infile.read()
final_list = []
for ind, val in enumerate(data.split('\n')):
    final_list.append(val)
    if val == 'AAXX':
        final_list.insert(-3, 'HELLO')
# save the text file
with open('test.txt', 'w') as outfile:
    data = outfile.write('\n'.join(final_list))

输出:

HELLO
111
222
AAXX
HELLO
333
444
AAXX
HELLO
555
666
AAXX