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}}
如果您避免在名称中使用无效字符,您可以使用与上述相同的方法,并且只需要省略顶级字典即可。
添加回答
举报