簡體   English   中英

從Apache日志文件中獲取Pandas數據幀

[英]Getting a Pandas dataframe from an Apache log file

我有一個日志文件,其中包含1,770,781行表單

[02/Jan/2015:08:08:43] "GET /click?article_id=139&user_id=19550 HTTP/1.1" 200 3078

我想提取時間,article_id和user_id,並以方便的格式將它們組合起來進行分析。 現在,我有以下代碼提取這些元素並嘗試將它們組合在Pandas DataFrame中:

logs = pd.DataFrame(columns=['time', 'article_id', 'user_id'])
regex = '\[(?P<time>.*?)\] "GET (.*?=)(?P<article_id>\d+)(&.*?=)(?P<user_id>\d+)'

for line in log_file:
    time = re.match(regex, line).group('time')
    article_id = re.match(regex, line).group('article_id')
    user_id = re.match(regex, line).group('user_id')
    logs.append([time, article_id, user_id])

但這需要永遠運行,我開始認為我應該放棄這種方法。 有沒有辦法讓這個更有效率? 嘗試這樣做是否真實可行? 如果沒有,是否有更好的方法來獲取這些數據?

你沒有使用re.compile ,當你在循環中有一次足夠的時候,你也沒有效率地匹配三次。

logs = pd.DataFrame(columns=['time', 'article_id', 'user_id'])
# regc = re.compile(r'\[(?P<time>.*?)\] "GET (.*?=)(?P<article_id>\d+)(&.*?=)(?P<user_id>\d+)')
# alternative regexp that might be more efficient
regc = re.compile(r'\[(?P<time>.+)\] "GET (?:.+article_id=)(?P<article_id>\d+)(?:&user_id=)(?P<user_id>\d+)')

for line in log_file:
    m = regc.match(line)
    time = m.group('time')
    article_id = m.group('article_id')
    user_id = m.group('user_id')
    logs.append([time, article_id, user_id])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM