[英]Efficient way to parse large journalctl file to match keywords using Python
解析journelctl文件時,要查找的關鍵字是:錯誤,啟動,警告,回溯
遇到關鍵字后,我需要為每個關鍵字增加計數器並打印匹配的行 。
因此,我嘗試如下: 從文件中讀取它並使用Collections模塊-Counter對象與re.findall一起跟蹤計數:
import re
from collections import Counter
keywords = [" error ", " boot ", " warning ", " traceback "]
def journal_parser():
for keyword in keywords:
print(keyword) # just for debugging
word = re.findall(keyword, open("/tmp/journal_slice.log").read().lower())
count = dict(Counter(word))
print(count)
上面的解決方案解決了我的問題,但是我期待有更多有效的方法。
請指教。
這是一種更有效的方法:
def journal_parser(context):
with open("/tmp/journal_slice.log") as f:
data = f.read()
words = re.findall(r"|".join(keywords), data, re.I) # case insensitive matching by passing the re.I flag (ignore case)
count = dict(Counter(words))
print(count)
我不確定您是否仍然需要在關鍵字周圍留空格,具體取決於您的數據。 但是我認為在這里使用正則表達式和額外的庫是不必要的導入。
keywords = ["error ", " boot ", " warning ", " traceback "]
src = '/tmp/journal_slice.log'
def journal_parser(s, kw):
with open(s, 'r') as f:
data = [w for line in f for w in line.split()]
data = [x.lower() for x in data]
print(data)
for k in kw:
print(f'{k} in src happens {data.count(k)} times')
journal_parser(src, keywords)
請注意,打印中的f字符串格式在3.x早期的python中不起作用,也可能無需轉換為更低的格式-只需將所有預期的情況添加到關鍵字中,如果文件確實很大,則可以在在每一行上列出並執行list.count(),在這種情況下,您必須跟蹤計數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.