Counting the number of words in a CSV column and writing to another CSV?

I am working on a program to open a CSV file, count the number of times the words “Information”, “Low”, “Medium”, “High” and “Critical” appear, and write the results in another CSV. In the future, I want him to be able to analyze several CSVs that were formatted the same for this information and write all the results in one CSV. This is what I still have:

import sys
import csv
import collections

severity = collections.Counter()
with open(r'C:\Report.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        severity[row[3]] +=1

print(severity.most_common)
with open(r'C:\test.csv', 'a', newline='') as write_file:
    sevwrite = csv.writer(write_file, delimiter= ',',
                      quotechar=' ', quoting=csv.QUOTE_MINIMAL)
    sevwrite.writerow([severity.most_common])

He records full

<bound method Counter.most_common of Counter({'Info': 510, 'Medium': 30, 'Low': 24, 'High': 7, 'Severity': 1})>

to the file Test.CSV. Any help is appreciated.

+3
source share
1 answer

You need to call the method most_common:

print(severity.most_common())

and

sevwrite.writerow(severity.most_common())

, , .most_common() ; . sevwrite.writerow() ( [...]) :

('Info', 510),('Medium', 30),('Low', 24),('High', 7),('Severity', 1)

. .most_common() ( ), CSV, , .

CSV , , , . ; , CSV.

csv.DictWriter():

with open(r'C:\test.csv', 'a', newline='') as write_file:
    sevwrite = csv.DictWriter(write_file, ('High', 'Severity', 'Medium', 'Info', 'Low'))
    sevwrite.writerow(severity)

. csv.DictWriter() , .

, :

import csv

from collections import Counter

with open(r'C:\Report.csv', 'r') as f:
    reader = csv.reader(f)
    severities = Counter(r[3] for r in reader)

- , Counter.

, , :

import csv

from collections import Counter

with open(r'C:\test.csv', 'w', newline='') as write_file:
    sevwrite = csv.DictWriter(write_file, ('High', 'Severity', 'Medium', 'Info', 'Low'))
    sevwrite.writeheader()

    for filename in list_of_filenames:
        with open(r'C:\Report.csv', 'r') as f:
            reader = csv.reader(f)
            severities = Counter(r[3] for r in reader)
            sevwrite.writerow(severities)

( ); sevwrite.writeheader().

+2

All Articles