参考链接
微信搜索我吃你家米了关注公众号
想在网站上添加站长之家的统计脚本
但是不知道怎可麽添加
于是用了一个笨方法,直接遍历所有html文件,将footer替换掉
由于是多行替换,需要先使用strip将多行文本转换为单行文本,然后使用replace进行替换
具体代码如下:
render.py:
import os
import fileinput
def get_filelist(dir):
newDir = dir
if os.path.isfile(dir):
if os.path.splitext(dir)[-1] == ".html":
replace(dir)
elif os.path.isdir(dir):
for s in os.listdir(dir):
newDir=os.path.join(dir,s)
get_filelist(newDir)
def replace(dir):
after = """<footer id="contentinfo" class="body"> <address id="about" class="vcard body"> Proudly powered by <a href="http://getpelican.com/">Pelican</a>, which takes great advantage of <a href="http://python.org">Python</a>. </address><!-- /#about --><p>The theme is by <a href="http://coding.smashingmagazine.com/2009/08/04/designing-a-html-5-layout-from-scratch/">Smashing Magazine</a>, thanks!<br/><script type="text/javascript">document.write(unescape("%3Cspan id='cnzz_stat_icon_1278862900'%3E%3C/span%3E%3Cscript src='https://s9.cnzz.com/z_stat.php%3Fid%3D1278862900%26show%3Dpic' type='text/javascript'%3E%3C/script%3E"));</script></p> </footer><!-- /#contentinfo -->"""
before = """<footer id="contentinfo" class="body"> <address id="about" class="vcard body"> Proudly powered by <a href="http://getpelican.com/">Pelican</a>, which takes great advantage of <a href="http://python.org">Python</a>. </address><!-- /#about --> <p>The theme is by <a href="http://coding.smashingmagazine.com/2009/08/04/designing-a-html-5-layout-from-scratch/">Smashing Magazine</a>, thanks!</p> </footer><!-- /#contentinfo -->"""
#read input file
print(dir)
fin = open(dir, "rt")
#read file contents to string
lines = fin.readlines()
data = '\t'.join([line.strip() for line in lines])
#replace all occurrences of the required string
data = data.replace(before, after)
#close the input file
fin.close()
#open the input file in write mode
fin = open(dir, "wt")
#overrite the input file with the resulting data
fin.write(data)
#close the file
fin.close()
if __name__ =="__main__":
get_filelist("/var/www/html")
大致思想就是将文件打开,然后将data变量处理成单行的,然后再使用replace进行替换,最后将修改完成后的内容写回到文件中