2013-07-20 54 views
0

我有下面的代碼很好用。它將我的IP地址從一個文件中取出並計算它們出現在日誌文件中的次數。基於計數的字典排序

def count_ips(): 
    fp=open('logfile','r') 
    store=[] 
    while 1: 
      line=fp.readline() 
      if not line: 
        break 
      if line[-1:] == '\n': 
        line=line[:-1] 
      data1=line.split('"') 
      data2=data1[0].split(' ') 
      store.append({'IP':data2[0],'Date':data2[3]+' '+data2[4],'Action':' '.join(data1[1:-2]),'Browser':' '.join(data1[-2:])}) 
    fp.close() 
    count={} 
    for i in store: 
      if i['IP'] in count: 
        count[i['IP']] +=1 
      else: 
        count[i['IP']] =1 

    avg=0 
    cnt=0 
    for i in count: 
      avg+=count[i] 
      cnt+=1 
    avg=avg/cnt 
    print 'average hit is: %i' % avg 

    for i in count: 
      if count[i] > 10: 
        print i +' %i' % count[i] 
count_ips() 

我真的不知道我是如何得到這一點,但在這一節。在打印出來之前,我想按計數進行排序。底部最大的數字。

for i in count: 
      if count[i] > 10: 
        print i +' %i' % count[i] 

我覺得在這一點上我只是看着事情錯了,沒有看到我的小難題的簡單解決方案。

謝謝你的幫助! 傑森

回答

2

假設count是你的IP-的字典>計數,然後:

from operator import itemgetter 
sorted_counts = sorted(count.iteritems(), key=itemgetter(1)) 
for ip, cnt in sorted_counts: 
    print ip, 'had', cnt, 'results' 
+0

有時我覺得我永遠不會得到這個。非常感謝您的幫助! – JasonOrtiz

0

所以假設你有哪些含有對IP和值是計數鍵的字典d。

>>> d = {'1.1.1.1':5, '2.2.2.2':4} 

這裏是什麼,我會在一個班輪做:

>>> sorted((d[ip], ip) for ip in d) 
[(4, '2.2.2.2'), (5, '1.1.1.1')] 

您還可以使用參數反向= true來排序以相反的順序列表。