python - 从 Apache 日志文件获取 Pandas 数据框

标签 python apache pandas optimization

我有一个包含 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,而且您还在低效地匹配了 3 次,而在循环中一次就足够了。

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])

关于python - 从 Apache 日志文件获取 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34950066/

相关文章:

python - 如何将 Google Appengine Python 运行时 2.7 迁移到 3.7?

python - 使用 XPath、Python 和 Scrapy 解析 HTML

python - 如何将 Django 模型表限制为一行

python - 枚举属性的属性?

linux - SSL 证书安装 apache 2 不工作

php - 缺少临时文件夹

python - 连接两列并获得新列

php - 保护文件不被直接访问

python - 如何将数据框中的第二列除以第一列?

python - 如何避免 Pandas 直方图子图中的图标题和轴标题重叠?