3 回答

TA貢獻1893條經驗 獲得超10個贊
? ?error_pattern = r'ticky: ERROR ([\w\s\']*) \((.+)\)'
? ? info_pattern = r'ticky: INFO.* \((.+)\)'
? ? user_stat = {}
? ??
? ? with open('syslog.log','r') as logs:
? ? ? for line in logs.readlines():
? ? ? ? if re.search(error_pattern,line):
? ? ? ? ? results = re.search(error_pattern, line)
? ? ? ? ? user_stat.setdefault(results.group(2),[0,0])[1]+=1
? ? ? ? if re.search(info_pattern,line):
? ? ? ? ? results = re.search(info_pattern, line)
? ? ? ? ? user_stat.setdefault(results.group(1),[0,0])[0]+=1
? ??
? ? user_sorted = sorted(user_stat.items())
? ??
with open('user_statistics.csv','w') as output:
? csvfiler = csv.writer(output)
? csvfiler.writerow(['Username','INFO','ERROR'])
? for item in user_sorted:
? ? ? onerow = [item[0],item[1][0],item[1][1]]
? ? ? csvfiler.writerow(onerow)

TA貢獻1804條經驗 獲得超3個贊
嘗試這個:
import re
# As I don't have access to the original file, you can
# uncomment the code below to get the lines from the file
#with open('filename.txt') as file:
# lines = file.readlines()
# Now, assuming these are the lines from the log file
lines = [
'Aug 9 12:44:39 hostnameABC gnome-terminal-[12581]: Theme parsing error: gtk.css:6765:28: Missing opening bracket in color definition',
'Aug 9 12:44:39 hostnameABC gnome-terminal-[12581]: Theme parsing error: gtk.css:6765:28: Missing opening bracket in color definition',
'Aug 9 12:44:39 hostnameABC gnome-terminal-[1581]: Theme parsing error: gtk.css:6765:28: Missing opening bracket in color definition'
]
er_regex = re.compile(r'gnome-terminal-\[\d+\]')
def er_count():
count = {}
er_ins = er_regex.findall(' '.join(lines))
for er in er_ins:
count.setdefault(er, 0)
count[er] += 1
return(count)
print(er_count())
您會得到一本字典,其中包含每個錯誤的計數:)

TA貢獻1812條經驗 獲得超5個贊
您不能在變量名稱中使用連字符和方括號。您可以通過使用更高級別的字典來解決這個問題,這樣帶有連字符和方括號的名稱就是該字典中的鍵。您的解決方案可能如下所示:
import re
log = '''Aug 9 12:44:39 hostnameABC gnome-terminal-[12581]: Theme parsing error: gtk.css:6765:28: Missing opening bracket in color definition
Aug 9 12:44:39 hostnameABC gnome-terminal-[12581]: Theme parsing error: gtk.css:6765:28: Missing opening bracket in color definition
Aug 9 12:44:39 hostnameABC gnome-terminal-[12581]: Info only'''
data = {}
matches = re.findall(r'(gnome-terminal-\[\d+\])(?=.*error)', log)
for match in matches:
data[match] = data.setdefault(match, {'ERROR': 0})
data[match]['ERROR'] += 1
print(data)
# {'gnome-terminal-[12581]': {'ERROR': 2}}
如果您避免在名稱中使用無效字符,您可以使用與上述相同的方法,并且只需要省略頂級字典即可。
添加回答
舉報