关于python的find-replace-text有很多线程,但我认为我的问题不同。
我有一堆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())

这并不完美——它只在字符串不包含任何转义引号(即\")的情况下才起作用——但希望它能做到这一点。

09-25 17:01
查看更多