Group: PYTHON WORKSHOP

string 的replace 方法 和 正则表达式re.sub 速度比较
lidongok | Sep 19, 2007 2:45:11 PM
# 目的是把网页源代码中的 form 表单的提交方式由POST修改为 GET, 实现方法有多种,但是比较常见的就是字符串替换方法和使用正则表达式替换两种,下面对两种方法进行一下速度比较.

# TEST SPEED , String.replace VS re.sub
import re
import time

if __name__ == '__main__' :

file = open('test.htm','r')
# this test.htm file is about 100KB size,have 4 method='post'
matchstr = file.read()
file.close()
#starttime = time.time()
for i in range(10000):
matchstr.replace('method="post"','method="get"')
matchstr.replace('method="POST"','method="get"')
matchstr.replace('method=post','method="get"')
matchstr.replace('method=POST','method="get"')
matchstr.replace("method='POST'",'method="get"')
matchstr.replace("method='post'",'method="get"')

endtime = time.time()

#print newstr
print "str.replace method excute 10000 times , used %s seconds" %(endtime-starttime)

starttime = time.time()
rawstr = r"""method=["|']?post["|']?"""
compile_obj = re.compile(rawstr, re.IGNORECASE| re.DOTALL)
for i in range(10000):
newstr = compile_obj.sub('method="GET"',matchstr, 0)
endtime = time.time()
print "re.sub method excute 10000 times , used %s seconds" %(endtime-starttime)


# 执行结果如下:
#str.replace method excute 10000 times , used 15.0780000687 seconds
#re.sub method excute 10000 times , used 28.6560001373 seconds
看来,还是用正则表达式慢一点。不过这个测试对于re.sub有点不公平,因为前面的字符串替换测试并不能完全和后面的正则表达式达到相同的效果。比方说 method="PoSt" 字符串匹配就给漏掉了。而后面的正则替换就不会。而如果先用s.lower() 方法去比较虽然速度会提高,但是就破坏了原来的网页源代码的风格了。
#所以用正则表达式还是很强大的。

编写这个程序的时候参考了
http://wiki.ubuntu.org.cn/Python%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%93%8D%E4%BD%9C%E6%8C%87%E5%8D%97
同时到这个网站 http://kodos.sourceforge.net/home.html
下载了Kodos这个专门测试python正则表达式的工具,对我很有帮助。
这篇文章作者:李东
创作日期:2007-09-19



Comment: (1 replies total, Click here for more)


09/19/2007 lidongok
哇塞,缩进格式都丢了. 直接拷贝下来肯定不能执行了.

To post your comment, Please login first.