2015-04-03 85 views
0

我試圖按年計算每月 日曆月(12月,1月,2月,...)網絡服務器的點擊次數。Python 2.7 - 查找網絡服務器點擊次數

我對Python很新,所以我甚至不知道從哪裏開始。我想你必須使用一些字符串拆分或正則表達式。

我給出以下輸出日誌文件:

[31/Dec/1994:23:55:08 -0700] "GET 45.html HTTP/1.0" 200 5489 
remote - - [31/Dec/1994:23:56:55 -0700] "GET 2195.ps HTTP/1.0" 200 522318 
remote - - [31/Dec/1994:23:59:37 -0700] "GET 957.ps HTTP/1.0" 200 122146 
remote - - [01/Jan/1995:00:31:54 -0700] "GET index.html HTTP/1.0" 200 2797 
remote - - [01/Jan/1995:00:31:58 -0700] "GET 2.gif HTTP/1.0" 200 2555 
remote - - [01/Jan/1995:00:32:33 -0700] "GET 3.gif HTTP/1.0" 200 36403 
remote - - [01/Jan/1995:01:39:21 -0700] "GET 20.html HTTP/1.0" 200 378 
local - - [01/Jan/1995:01:47:41 -0700] "GET index.html HTTP/1.0" 200 2797 
local - - [01/Jan/1995:01:47:49 -0700] "GET 39.html HTTP/1.0" 200 669 
local - - 
+1

您的預期輸出是什麼? – 2015-04-03 06:34:17

+1

我印象深刻你有一個20歲的日誌文件:p – 2015-04-03 07:25:30

回答

0

分割更容易(IMO)比應用正則表達式。

def year_month(s): 
    try: 
     discard, month, rest = s.split('/', 2) # split twice on '/' 
    except ValueError: 
     return None # for last line without/
    year = rest.split(':', 1)[0] 
    year = int(year) # optional 
    return year, month 

您可以使用返回的元組,從這個功能作爲重點的一些詞典::

d = {} 
for line in open('yourfile'): 
    ym = year_month(line) 
    if ym is None: 
     continue 
    x = d.setdefault(ym, [0]) 
    x[0] += 1 
for ym in sorted(d): 
    print('Year: {0}, Month: {1}, Hits: {2}'.format(ym[0], ym[1], d[ym][0])) 

如果你願意,你可以通過傳遞一個日誌行提取與下面的函數,這些值請使用正則表達式替換year_month()部分:

import re 

# see https://docs.python.org/2/howto/regex.html 
year_month_pattern = re.compile(r""" 
.*/ 
(?P<month>.*) 
/
(?P<year>\d*) 
:.* 
""", re.VERBOSE) 

def year_month(s): 
    res = year_month_pattern.match(s) 
    if res is None: 
     return None 
    try: 
     return int(res.group('year')), res.group('month') 
    except ValueError: 
     pass 
+0

謝謝。沒有更改您的代碼 - 我得到以下錯誤------- Traceback(最近呼叫最後): 文件「C:\ Hadoop-stat-class \ apache1.py」,第18行,在 print ('Year:{0},Month:{1},Hits:{2}'.format(ym [0],ym [1],d [ym] [0])) TypeError:'int'object has沒有屬性'__getitem__' – user4745212 2015-04-03 07:52:30

+0

@ user4745212即year_month函數中的0,應該是None。我手工編輯而不是複製我的(工作)代碼。 – Anthon 2015-04-03 08:08:55

+0

對不起。新的python,不知道要改變什麼來擺脫TypeError。 – user4745212 2015-04-03 13:10:46