Skip to main content
 首页 » 编程设计

python之查找并替换 POM 中两个单词之间的内容

2025年05月04日12soundcode

需要 bash 脚本或 python 脚本来查找和替换两个标签之间的文本?

例如:

<start>text to find and replace with the one I give as input<end> 

'要查找并替换为我作为输入提供的文本'只是一个示例,它可能每次都不同。

我想做类似 ./changetxt inputfile.xxx newtext 的事情

其中 changetxt 有脚本; inputfile.xxx 包含需要更改的文本,newtext 是 inputfile.xxx 中的内容

请您参考如下方法:

python :

import sys 
 
if __name__ == "__main__": 
    #ajust these to your need 
    starttag = "<foo>" 
    endtag = "</foo>" 
 
    inputfilename = sys.argv[1] 
    outputfilename = inputfilename + ".out" 
    replacestr = sys.argv[2] 
 
    #open the inputfile from the first argument 
    inputfile = open(inputfilename, 'r') 
    #open an outputfile to put the result in 
    outputfile = open(outputfilename, 'w') 
 
    #test every line in the file for the starttag 
    for line in inputfile: 
        if starttag in line and endtag in line: 
            #compose a new line with the replaced string 
            newline = line[:line.find(starttag) + len(starttag)] + replacestr + line[line.find(endtag):] 
            #and write the new line to the outputfile 
            outputfile.write(newline) 
        else: 
            outputfile.write(line) 
     outputfile.close() 
     inputfile.close() 

将其保存在 replacetext.py 文件中并以 python replacetext.py\path\to\inputfile "I want this text between the tags"运行