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

问题描述 投票:-1回答:2

我想找到“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
python loops line add
2个回答
0
投票

你能尝试以下方法吗?

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

0
投票
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)

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

© www.soinside.com 2019 - 2024. All rights reserved.