# -*- coding:UTF-8 -*-
import os
import sys
import re
import traceback
import time
import string
reload(sys)
sys.setdefaultencoding('utf8')
"""
使用try提高代码效率
统计列表中字符串出现次数
调用自己写的函数,map比for循环更慢。
这个方法确实很牛,巧妙运用字典和异常,让代码只需遍历一次。
可应用在搜索引擎,相当于hash。
"""
RATETIMES = 200000 # 列表放大倍数,100万倍
count = {}
def tryCount(s):
try:
count[s] += 1
except KeyError:
count[s] = 1
if __name__ == "__main__":
try:
t1 = time.time()
log = "日志.txt".encode("gbk")
ofi = open(log, "w")
list = ['I', 'You', 'Python ', 'Perl']
lst = list * RATETIMES
print >> ofi, "计算字符串数列 ['I', 'You', 'Python ', 'Perl'] 中每个词出现的次数"
"""
for循环
0.18700003624 s
0.18700003624 s
"""
for s in lst:
try:
count[s] += 1 # 字符串第一次出现一定会抛关键字错误KeyError,进入except以后给count[s]赋个值下次就不会报错。
except KeyError: #这里指定捕捉KeyError,防止因为其他错误进入分支,如变量名不存在NameError,语法错误SyntaxError。
count[s] = 1
except: # 短短一句话一般没什么问题这里可以不要,我是在尝试捕捉除了KeyError以外的其他错误。
print >> ofi, ("%s" % traceback.format_exc())
break
"""
map循环
0.46799993515 s
0.469000101089 s
"""
count = {}
map(lambda s: tryCount(s), lst)
print >> ofi, count
except:
print >> ofi, ("%s" % traceback.format_exc())
finally:
t2 = time.time()
print >> ofi, (t2-t1),"s"
ofi.close()
os.startfile(log)