简体   繁体   中英

Python - Number of words counting from a csv file

I have a Server-Update-list with many entries like this (separated by commas in a CSV):

server1,SLES-SAP 15.1,Library,SUSE-SLE-Module-Python2-15-SP1-2020-3115,security,2020-11-02,2020-11-03 03:15:47 UTC,moderate,"python,python-base,python-curses,python-devel,python-gdbm,python-xml",7910,false
server1,SLES-SAP 15.1,Library,SUSE-SLE-Module-Basesystem-15-SP1-2020-3115,security,2020-11-02,2020-11-03 03:18:07 UTC,moderate,"libpython2_7-1_0,python,python,python-base,python-base",7911,false

I want to count all entries in the ""-fields (the depending Linux packages) that needs to be updated.

For example, in the first line, the entries "python,python-base,python-curses,python-devel,python-gdbm,python-xml" need to be counted, only the number of packages, not the names.

My target is to have a list like this:

server1: Number of Updates: 11 (6 from the first line + 5 from the second line)

How is this possible?

Thank you very much!

A simple solution involving the standard csv package and a dict would look like this:

import csv

server_updates = {}

with open("test.csv") as csv_file:
    reader = csv.reader(csv_file)
    for line_no, line in enumerate(reader):
        server, updated_pkgs = line[0], line[8]
        num_updates = len(updated_pkgs.split(","))

        if server not in server_updates:
            server_updates[server] = {}
        server_updates[server][line_no + 1] = num_updates


print(server_updates)  # {'server1': {1: 6, 2: 5}}

Since the updated packages field is a comma separated string you can split it on the comma and then you can get the length of the returned list, then you can count the number of updates of individual lines with the server_updates collection dictionary. Later you can use this dictionary to derive your target output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM