Skip to main content
 首页 » 编程设计

python之在 Python 中搜索、插入和替换文本的前一行

2025年02月15日8lyhabc

我有一个包含以下信息(示例)的文本文件

a = text1 text2 text3 text4   
b = text1 text8 text9 text5  
c = text6 text5 text1 text9    
d = text5 text4 text2 text9 

等等……

我想做的是找到一个组合,例如,text8 text9 将其替换为text10 并在其旁边创建一个新句子。最终结果将类似于:

a = text1 text2 text3 text4 
b = text1 text8 text9 text5 
b1 = text1 text10 text5 
c = text6 text5 text1 text9 
d = text5 text4 text2 text9 

到目前为止我已经做了这样的事情(我是 python 的新手):

import re 
 
text = open('file.txt').read() 
match_found=False 
matches = re.finditer('text2', text) 
m = None 
for m in matches: 
    match_found = True 
    pass 
if (match_found): 
    m.start() 
    m.end() 
text[1:m.end()] + "text10" + text[(m.end()+1):] 

但什么也没有发生,而且该行可以出现在其他句子中,例如:

a = text1 text2 text3 text4 
b = text1 text8 text9 text5 
b1 = text1 text10 text5 
c = text6 text5 text1 text9 
d = text5 text4 text8 text9 
d1 = text5 text4 text10 

请您参考如下方法:

我们可以将所有文件行存储在一些列表 inlines 中,然后遍历每一行并找到 'text8 text9' 并将其替换为 'text10' 然后将旧行和新行存储在新列表 outlines 中,以供以后使用。

由于问题歧义的假设:我们使用 str.replace 的第三个参数来仅替换字符串的第一次出现。

inlines = [line for line in open('in.txt', 'r')] 
outlines = [] 
for line in inlines: 
    label = line.split(' ')[0] 
    newline = line.replace('text8 text9', 'text10', 1).replace(label, f'{label}1', 1) 
    outlines.append(line) 
    outlines.append(newline) 
 
    # To print the lines as well we can add this 
    print(line) 
    print(newline)