In a file, I want to find a specific content(lines or lines) based on a string pattern, make changes to it, and replace it.
(在文件中,我想根据字符串模式查找特定的内容(行或行),对其进行更改并替换。)
The pattern can appear multiple times. (该图案可以出现多次。)
The file can contain code, (python or c). (该文件可以包含代码(python或c)。)
The string pattern can have multiple forms so I thought using regex, like:
(字符串模式可以有多种形式,所以我认为使用正则表达式,例如:)
custom_log("lorem ipsum can be anything ....")
or
(要么)
custom_log("lorem ipsum"
"can be anything")
or
(要么)
custom_log("""lorem ipsum
can be anything""")
The quotes can be simple or double.
(引号可以是简单的也可以是双引号。)
I start by going line by line, and search for a pattern
(我从逐行开始,然后搜索模式)
with open(filepath, mode="r") as f:
for line in f.readlines():
if "pattern" in line
but the issue, is that the content that I search it can be one one line or multiple lines, and between quotes can be anything as a string.
(但是问题是,我搜索的内容可以是一行或多行,而引号之间可以是字符串。)
I can't use a simple replace, because I need to get the content, passed to a function, change/adapt the content and pass it back to be written to file.
(我不能使用简单的替换,因为我需要获取内容,将其传递给函数,更改/调整内容,然后将其传递回回写入文件。)
I want to keep the initial formatting of the file.
(我想保留文件的初始格式。)
ask by user3541631 translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…