统计
#_*_coding:utf-8_*_
import operator
f = open("monitor_down.log")
# 初始化空字典,key为行内容,value为该行出现的次数
result = {}
for line in f:
line = line.strip()
# setdefault(key[, default]): If key is in the dictionary, return its value. If not, insert key with a value of default and return default.
count = result.setdefault(line,0)
count += 1
result[line] = count
#
# 以 key 为排序字段对整行进行 reverse 排序,operator.itemgetter():
# Return a callable object that fetches item from its operand using the operand’s __getitem__() method.
# If multiple items are specified, returns a tuple of lookup values.
sorted_result = sorted(result.iteritems(), key=operator.itemgetter(1),reverse=True)
for k,v in sorted_result:
print k,": ",v