Text 查找行,替换多行

Text 查找行,替换多行,text,python,Text,Python,有很多关于查找python替换文本的线程,但我认为我的问题是不同的 我有一堆带有 System.out.println("some text here"); 我正在尝试编写一个python脚本,用 if (logger.isInfoEnabled()) { logger.info("some text here"); } 为此,我尝试过: def findReplace(fileName, sourceText, replaceText): file = open(fileN

有很多关于查找python替换文本的线程,但我认为我的问题是不同的

我有一堆带有

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())

这并不完美——它只在字符串不包含任何转义引号(即
\“
——但希望它能起到作用。

你肯定会遇到麻烦,因为替换匹配的分隔符很困难。一种对我来说更有意义的方法——原因不止一个——是定义一个新的java函数
log\u if\u enabled
,然后用
log\u if\u enabled
替换
System.out.println
。这样,您就不必担心进行任何花哨的支架匹配。此外,在函数中封装
if
语句也是干的

不,那不行。在进行任何字符串连接之前,您需要检查log4j是否已启用。请参阅:性能部分。@dublintech:senderle的意思是,如果启用了函数,您应该编写新的
log\u(或您想命名的任何函数),以便它进行检查。也就是说,你的
if
语句应该在这个新函数中。是的,但是到了那个阶段,连接已经发生,并且造成了损害。如果启用(“my output=“+output+”,在此服务器上=“+servername”),它将作为日志调用;这种方法只有在从不连接的情况下才有效。“你在登录时通常都是这样的。”dublintech,啊,我明白你的意思。并不是说它不起作用,只是效率不高。既然我不知道你的具体情况,我就不指控你了。我会偷偷地插入对它的引用,以防万一:)@senderis-ha。使用ArrayList而不是vectors的人是否也在进行过早的优化:-)?您可以使用r''System\.out\.println(“(.+?)(?=”)”)”);''在结束序列之前懒散地提取所有字符”);当然,惰性搜索部分地解决了这个问题(尽管我不确定是否真的需要前瞻?)。但是,字符串包含
\“;)
总是会有问题。@bluepnume当我尝试你的时,我被告知括号太多。对不起,我不擅长正则表达式,有什么提示吗?dublintech:很抱歉,小的打字错误。现在修复。