2012-03-20 46 views
2

需要使用bash脚本或python脚本来查找和替换两个标签之间的文本?查找和替换POM中两个单词之间的内容

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

+0

行,就是更加清晰。我只需要知道你将如何确定要改变的文字。它总是在相同的标签之间还是会有所不同? – RickyA 2012-03-21 09:15:46

+0

@RickyA - 它总是在相同的标签 – user1164061 2012-03-21 16:15:25

回答

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文件并运行为蟒蛇replacetext.py \路径\到\ inputfile中“我想要的标签之间的这段文字”

+1

我不认为这就是OP的含义。 。 。 – ruakh 2012-03-20 20:21:37

+0

“替换两个标签之间的文本”.. – 2012-03-20 20:22:40

+0

不,我也认为他不是这个意思,但这是他要求的...... – RickyA 2012-03-20 20:27:41

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> 
+0

是的,但这个例子不是HTML也不是XML – 2012-03-20 20:42:59

+0

@Niklas B - 优点:( – fraxel 2012-03-20 20:45:21

相关问题