#!/usr/bin/python # -*- coding: utf-8 -*- #RUN // 程序啓動 #EXIT // 程序退出 #START // 熱點啓動 #STOP // 熱點停止 #ONL // 客戶端上線 #OFFL // 客戶端下線 #INSTALL //安裝 #UNINSTALL //卸載 import re #模式匹配UUID patternUid=re.compile(r'(\w){8}-(\w){4}-(\w){4}-(\w){4}-(\w){12}') #定義Uid字典,用來排重 uid={} #用來統計各種動作的次數 actionCount={ "a=RUN":0, "a=EXIT":0, "a=START":0, "a=STOP":0, "a=ONL":0, "a=OFFL":0, "a=INSTALL":0, "a=UNINSTALL":0 } for k,v in actionCount.iteritems(): with open("C:/Users/Administrator/Desktop/python/result.txt") as f: for line in f: if patternUid.search(line): uidName=patternUid.search(line).group() if k in line: if uid.has_key(uidName): pass else: uid[uidName]=1 actionCount[k]+=1 uid.clear() for k,v in actionCount.iteritems(): print k ,actionCount[k] ---------------------------------- 結果時間: C:\Python27\python.exe C:/Users/Administrator/Desktop/python/test3.py a=EXIT 42 a=START 404 a=INSTALL 0 a=STOP 228 a=UNINSTALL 0 a=RUN 45 a=ONL 274 a=OFFL 229 total time is : 2.03400015831
優化方法二
#!/usr/bin/python # -*- coding: utf-8 -*- #RUN // 程序啓動 #EXIT // 程序退出 #START // 熱點啓動 #STOP // 熱點停止 #ONL // 客戶端上線 #OFFL // 客戶端下線 #INSTALL //安裝 #UNINSTALL //卸載 import re import time import sys start_time=time.time() #模式匹配UUID patternUid=re.compile(r'(\w){8}-(\w){4}-(\w){4}-(\w){4}-(\w){12}') #定義時間 yesterday=time.strftime('%Y-%m-%d',time.localtime(time.time()-24*60*60)) #定義Uid字典,用來排重 uid={} actionCount={ "a=RUN":0, "a=EXIT":0, "a=START":0, "a=STOP":0, "a=ONL":0, "a=OFFL":0, "a=INSTALL":0, "a=UNINSTALL":0, "a=AUTORUN":0 } with open("C:/Users/Administrator/Desktop/python/28.log") as f: for line in f: if patternUid.search(line): uidName=patternUid.search(line).group() for k,v in actionCount.iteritems(): if k in line: if uid.has_key(uidName+k): uid[uidName+k]+=1 else: uid[uidName+k]=1 actionCount[k]+=1 for k,v in actionCount.iteritems(): print k,v end_time=time.time() print "total time is:",end_time-start_time --------------------------------- 結果時間: C:\Python27\python.exe C:/Users/Administrator/Desktop/python/test4.py a=EXIT 42 a=START 404 a=INSTALL 0 a=AUTORUN 236 a=STOP 228 a=UNINSTALL 0 a=RUN 45 a=ONL 274 a=OFFL 229 total time is: 0.287000179291