在POM中找到并替换两个单词之间的内容

时间:2012-03-20 20:17:26

标签: python bash

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

E.g:

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

'用我作为输入的那个查找和替换的文本'只是一个例子,每次都可以变化。

我想做类似./changetxt inputfile.xxx newtext

的事情

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

的内容

2 个答案:

答案 0 :(得分:1)

蟒:

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 \运行到\ inputfile“我想在标签之间使用此文本”

答案 1 :(得分:0)

您也可以使用BeautifulSoup来解决此问题:

  

如果设置了标记的.string属性,则替换标记的内容   用你给的字符串:

markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup)

tag = soup.a
tag.string = "New link text."
tag
# <a href="http://example.com/">New link text.</a>