I'm doing an exercise but I'm a bit stuck. I need to parse through a text file that has ERROR or INFO messages attached to a username. I then need to create a dictionary where I have the username as the key and one value being the amount of ERROR messages, and the other value being the amount of INFO messages. I will then put that in a CSV file where I need the header for the key to be "Username" and the other two headers be "ERROR" and "INFO"
Basically the finished result needs to look like this:
The part I'm stuck at is the first bit where I need to update a dictionary with the username as key and the amount of messages as values.
This is the code I have so far where I've only been able to figure out how to grab the amount of messages for the username but they're in two separate dictionaries:
import re
import csv
from collections import Counter
test_list = []
test_list2 = []
with open(r"syslog.txt", "r") as log:
for i in log:
if re.findall("ERROR.*", i):
test_list.append(re.findall("ticky:.*ERROR [\w '].*\(([\w\.]*).*$", i))
elif re.findall("INFO.*", i):
test_list2.append(re.findall("ticky:.*INFO [\w '].*\(([\w\.]*).*$", i))
flattened = [val for sublist in test_list for val in sublist]
test_dict = Counter(flattened)
print(test_dict)
flattened2 = [val for sublist in test_list2 for val in sublist]
test_dict2 = Counter(flattened2)
print(test_dict2)
And here's a few lines from the syslog.txt:
Jan 31 05:18:45 ubuntu.local ticky: ERROR Tried to add information to closed ticket (sri)
Jan 31 05:23:14 ubuntu.local ticky: INFO Commented on ticket [#1097] (breee)
Jan 31 05:35:00 ubuntu.local ticky: ERROR Connection to DB failed (nonummy)
Jan 31 05:45:30 ubuntu.local ticky: INFO Created ticket [#7115] (noel)
Jan 31 05:51:30 ubuntu.local ticky: ERROR The ticket was modified while updating (flavia)
So now I need to figure out a way to get these values in the same dictionary while keeping the key. Preferably I want to do it without merging the two dictionaries and instead just create one dictionary from the start.
Any help is very much appreciated!
info = dict()
error = dict()
username = {'info': info, 'error': error}
users = {'username': username}
How to get values?
for user in users:
print(user['info'])
print(user['error'])
class User:
def __init__(self, username, info, error):
self.username = username
self.info = info
self.error = error
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments