简体   繁体   English

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

[英]Add text 2 lines before match in python

I am trying to find "AAXX" and add the word "Hello" two lines above:我试图找到“AAXX”并在上面两行添加“你好”这个词:

Input:
111
222
AAXX
333
444
AAXX
555
666
AAXX

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

I have managed to insert only one "Hello" two lines before the first "AAXX" by using the code below, but I cannot make it loop through the file and do the same for all "AAXX" matches.通过使用下面的代码,我设法在第一个“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")

So far, I get:到目前为止,我得到:

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)

You may wrap this up as you wish to deal with inputs/outputs.您可以将其打包,因为您希望处理输入/输出。 You need to fix up the case where "AAXX" occurs within the first two items, as you haven't defined what behaviour you want there.您需要修复前两项中出现“AAXX”的情况,因为您还没有定义您想要的行为。 The key issue is that modifying the list as you iterate over it is bad practice, in particular the later indices can be off because you've inserted earlier "HELLO"s.关键问题是在迭代时修改列表是不好的做法,特别是后面的索引可能会关闭,因为您插入了较早的“HELLO”。 A possible solution is to keep track of all the insertion indices, then do the insertions in reverse order, because inserting later in the list doesn't affect the earlier indices.一种可能的解决方案是跟踪所有插入索引,然后以相反的顺序进行插入,因为在列表中稍后插入不会影响较早的索引。

Can you try the following:您可以尝试以下操作:

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

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM