python替换

python的替换主要是利用python的正则表达,python的正则表达功能比较强大。我就介绍下我经常用的几个方法。可能说的详细,如果要深入研究的话。还是
要去看下python的文档了.
废话不多说。马上开始介绍
一般我会用re.compile来建立一个正则对象。python 文档上介绍好象这个会加快匹配的速度
link = re.compile(r'\d+')
然后生成的话。我就可以开始匹配了
content = link.search(content).groups()
或者
content = link.fetchAll(content)
返回一个列表
还有sub等方法
正则这块的话我也学的不好。所以有时匹配一些字符串的时候会吃力。冒大汗就当减肥,,,
下面上一段我写的代码:
import glob
import re
import string
image = re.compile(r'http://images.wauee.com/ring/|/static/')
dir = glob.glob(r"/home/workspace/ring/tag/*.html")
for i in dir:
xxx = open(i, 'r')
content =  xxx.readlines()
strcontent = ''
filecontent = []
for k in content:
new = image.sub('../static/', k)
filecontent.append(new)
strcontent = "".join(filecontent)
aa = open(i, 'w')
aa.write(strcontent)
print 'success'

评论回复