如何使用python在文件中为搜索的模式在下一行插入一个字符串?

2024-05-19 22:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件内容是以下:在

He is good at python.
Python is not a language as well as animal.
Look for python near you.
Hello World it's great to be here.

现在,脚本应该搜索模式“python”或“pyt”或“pyth”或“python”或任何与“p/python”相关的regex。在“特别的狮子”之后加上新的单词。所以输出应该变成以下:在

^{pr2}$

我怎么能做到呢?在

在注:- 直到现在我写的代码这:在

def insertAfterText(args):
    file_name = args.insertAfterText[0]
    pattern = args.insertAfterText[1]
    val = args.insertAfterText[2]
    fh = fileinput.input(file_name,inplace=True)
    for line in fh:
        replacement=val+line
        line=re.sub(pattern,replacement,line)
        sys.stdout.write(line)
    fh.close()

Tags: 文件name内容forisaslineargs
2条回答

你最好写一个新的文件,而不是试图写到一个现有文件的中间。在

with open是打开文件的最佳方式,因为一旦完成,它会为您安全可靠地关闭文件。下面是一种使用with open同时打开两个文件的酷方法:

import re

pattern = re.compile(r'pyt', re.IGNORECASE)

filename = 'textfile.txt'
new_filename = 'new_{}'.format(filename)

with open(filename, 'r') as readfile, open(new_filename, 'w+') as writefile:
    for line in readfile:
        writefile.write(line)
        if pattern.search(line):
            writefile.write('Lion\n')

在这里,我们打开现有文件,并打开一个新文件(创建它)以写入。我们循环输入文件,并简单地将每一行写入新文件。如果原始文件中的一行包含正则表达式模式的匹配项,那么在写入原始行之后,我们还将写入Lion\n(包括新行)。在

将文件读入变量:

with open("textfile") as ff:
  s=ff.read()

使用regex并将结果写回:

^{pr2}$

编辑: 要从命令行insert使用:

import sys
textfile=sys.argv[1]
pattern=sys.argv[2]
newtext=sys.argv[3]

并替换

r"(?mi)(?=.*python)(.*?$)",r"\1\nLion"

fr"(?mi)(?=.*{pattern})(.*?$)",r"\1{newtext}"

在open()中,将“textfile”改为textfile。在

相关问题 更多 >