# 目的是把网页源代码中的 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() 方法去比较虽然速度会提高,但是就破坏了原来的网页源代码的风格了。 #所以用正则表达式还是很强大的。