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

标签 python

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

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)

关于python - 在 Python 中搜索、插入和替换文本的前一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45069276/

相关文章:

python - 如何将 pandas 中的列拆分为具有特定分隔符位置的多列?

python - 如何使用标准 auth api 和 username=True 更改 web2py 中用户的电子邮件地址

python - python 中的 stdtr 在进行 t 检验时为 p 值提供 nan

python - 从 Python 中的列表 A 或 B 中随机选择每个索引的 1 个元素

python - socket,gethostbyaddr 的返回和写入文件如何拆分?

Python:如何从列表[-1]中获取错误?

python - 在 Keras 中实现标准化流程

python - 无法匹配正则表达式模式

python - [Learning Python]一书中说range是一个generator——这是假的吗?

python - 如何获取 Pandas DataFrame 最近 5 个月的数据?