Insert column names as ("Error", "Count") at the zero index position of the sorted "error" dictionary in python

Viewed 813
error_count = {}
user_count = {}
with open(argv[1], 'r') as f:
    for line in f:
        result1 = re.search(r" ticky: ERROR ([\w ]*) ",line)
        if result1 is not None:
            if result1[1] not in error_count:
                error_count[result1[1]] = 0
            else:
                error_count[result1[1]] += 1
print (sorted(error_count.items(), key = operator.itemgetter(1), reverse=True))

I need to search a logfile and find error messages and then sort them in a dictionary from most occurred to least occurred. I'm able to reach here.

Next, I need to Insert column names as ("Error", "Count") at the zero index position of the sorted "error_count" dictionary. And lastly, I need to create a CSV file out of that dictionary. I'm stuck here. Someone, please help me how to solve this.

1 Answers

The code you posted is incomplete and has many errors. It was missing all the import statements, wouldn't compile, and was using the regular expression result incorrectly. Your regular expression was unnecessarily complicated (requiring a trailing space character, for example).

Here is a complete, tested version:

import sys
import re
from collections import defaultdict
import operator
import csv

error_count = defaultdict(str)
user_count = {}
with open(sys.argv[1], 'r') as f:
    for line in f:
        result1 = re.search(r" ticky: ERROR (.+)", line)
        if result1 is not None:
            msg = result1.group(1).rstrip()
            if msg not in error_count:
                error_count[msg] = 1
            else:
                error_count[msg] += 1

with open('error_count.csv', 'w') as cf:
    cw = csv.writer(cf)
    cw.writerow(['Error', 'Count'])
    for error in sorted(error_count.items(), key = operator.itemgetter(1), reverse=True):
        cw.writerow(error)

I ran it on this input file:

 ticky: INFO  this is not an error
 ticky: ERROR this is an error
 ticky: ERROR this is an error
 ticky: ERROR this is another error
 ticky: ERROR this is yet still an error
 ticky: DEBUG this is not an error either
 ticky: ERROR AAA this is an error
 ticky: ERROR AAA this is an error
 ticky: ERROR BBB this is an error
 ticky: ERROR CCC this is an error
 ticky: ERROR DDD this is an error
 ticky: ERROR CCC this is an error
 ticky: ERROR DDD this is an error
 ticky: ERROR DDD this is an error

And the output file error_count.csv came out as:

Error,Count
DDD this is an error,3
this is an error,2
AAA this is an error,2
CCC this is an error,2
this is another error,1
this is yet still an error,1
BBB this is an error,1
Related