text - 查找行,替换多行

标签 text python

有很多关于 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/

相关文章:

swift - 如何使 UIButton 具有正确的图像和文本外观?

javascript - 图像描述网站

python - 过度拟合图像分类

python编写程序迭代csv文件以匹配字段并将结果保存在不同的数据文件中

xslt - 使用 datapower 将文本文件转换为 xml

file - 如何计算两个license.txt文件之间的相似度?

c - 在c中如何将int变量更改为字符串变量?

python - 使用python-asyncio时如何重载模块?

python - 将重复数据从行转换为列

python - 具有不同 x 和 y 误差的 Pyplot 误差线