gpt4 book ai didi

text - 查找行,替换多行

转载 作者:太空宇宙 更新时间:2023-11-03 13:22:28 26 4
gpt4 key购买 nike

有很多关于 find replace text for python 的话题,但我认为我的问题是不同的。

我有一堆java文件

System.out.println("some text here");

我正在尝试编写一个 python 脚本,它将全部替换为

if (logger.isInfoEnabled()) {
logger.info("some text here");
}

为此我尝试过:

def findReplace(fileName, sourceText, replaceText):
file = open(fileName, "r") #Opens the file in read-mode
text = file.read() #Reads the file and assigns the value to a variable
file.close() #Closes the file (read session)

file = open(fileName, "w") #Opens the file again, this time in write-mode
file.write(text.replace(sourceText, replaceText)) #replaces all instances of our keyword
# and writes the whole output when done, wiping over the old contents of the file
file.close() #Closes the file (write session)

并传入:

filename=Myfile.java, sourceText='System.out.println', replaceText='if (logger.isInfoEnabled()) { \n' \logger.info'

但是,我正在努力获取替换中的结尾 '。它需要围绕已经存在的相同输出字符串进行包装。有小费吗?

谢谢。

最佳答案

import re

sourceText = 'System\.out\.println\(("[^"]+")\);'

replaceText = \
r'''if (logger.isInfoEnabled()) {
logger.info(\1);
}'''

re.sub(sourceText, replaceText, open(fileName).read())

这并不完美——它仅在字符串不包含任何转义引号(即 \")时才有效——但希望它能解决问题。

关于text - 查找行,替换多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9385584/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com