繁体   English   中英

在字符串匹配后复制特定行,并使用它们替换另一个文件中的其他行

[英]Copying specific lines after a string match and using them to replace other lines in another file

我最近开始使用Python 3,我想知道这里有人是否可以帮助我弄清楚如何执行以下操作:

让我们假设我有一个看起来像这样的文件:

Line 0
'Phrase/String that I am looking for'
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6

我想做的是

(1)从文本文件的末尾开始,搜索特定的phrase/string

(2)找到字符串后,我想复制3-5行

(3)用原始文本文件中的3-5行替换另一个文件中的9-11行。

到目前为止,我只能找到我的字符串,但似乎无法弄清楚如何执行步骤2和3。这是我写的内容:

with open("myfile.txt", 'r') as searchfile:
     for line in reversed(list(searchfile)):
          if 'my string' in line:
               print(line)
searchfile.close()

再次,我尝试了其他一些操作,但是直到这一点我的脚本仍然有效。 所以,我只包括这个。

这将为您提供第1部分和第2部分中的3行。

 # (?m)[\S\s]*((?:^.*\r?\n){3})^.*phrase

 (?m)                  # Multi-line modifier
 [\S\s]*               # Greedy, grab all up to ->
 (                     # (1 start)
      (?:                   # Only 3 lines of unknown text
           ^ .* \r? \n 
      ){3}
 )                     # (1 end)
 ^ .* phrase           # Nex line contains phrase

不确定从头开始检查是否必要或合乎逻辑,因此如果我们找到该行并用islice提取我们想要的行,则仅遍历文件内容是否中断,然后使用inume = True的enumerate和fileinput.input修改另一个文件,并添加在适当位置添加新行:

from itertools import islice
from fileinput import input as inp
import sys

with open("in.txt") as f:
    sli = None
    for line in f:
        if line.rstrip() == 'Phrase/String that I am looking for':
            f.seek(0) # reset pointer
            sli = islice(f, 2, 5) # get lines 3-5, o based indexing
            break
    if sli is not None:
        for ind, line in enumerate(inp("other.txt",inplace=True)):
            if ind in {8,9,10}: # if current line is line 9 10 or 11 write the next line from sli
                sys.stdout.write(next(sli))
            else: # else just write the other lines
                sys.stdout.write(line)

other.txt:

1
2
3
4
5
6
7
8
9
10
11
12

后:

1
2
3
4
5
6
7
8
Line 1
Line 2
Line 3
12

暂无
暂无

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

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