Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sum similar items
#1
Greetings!
I'm trying to sum(count) similar items in a file.
File example:
PRQ09_PCX0161Host,DV1
PRQ09_PCX0170Host,PHQ
PRQ09_PCX0171Host,ATC
PRQ09_PCX0173Host,ATC
PRQ09_PCX0175Host,ATC
PRQ09_PCX0176Host,PHQ
PRQ09_PCX0179Host,DG2
PRQ09_PCX0180Host,TGP_H
PRQ09_PCX0183Host,PHQ
PRQ09_PCX0184Host,PHQ
PRQ09_PCX0280Host,TCP_H
PRQ09_PCX0380Host,TCP_H
I thought I could use 'counter' and it does count very nice and produces the right output but I cannot access the Key-Value for some reason.

Code:
prdcs = []

with open (prod_BY_host, 'r') as pr_host :
    for lnf in pr_host :
        lnf=lnf.strip()
        host,prName = lnf.split(',')
        prdcs.append(prName)
    print(Counter(prdcs))
    mout.write(str(Counter(prdcs)))
mout.close()  
It prints :
Counter({'PHQ': 4, 'ATC': 3, 'TCP_H': 2, 'DV1': 1, 'DG2': 1, 'TGP_H': 1})
How I can get (print to an output file) keys- values wihtuot the garbage?
Just this:
PHQ,4
ATC,3
TCP_H,2
DV1,1
DG2,1
TGP_H,1

Or maybe there is a better way to do this?
Thank you
Reply


Messages In This Thread
Sum similar items - by tester_V - Jun-29-2021, 04:09 AM
RE: Sum similar items - by bowlofred - Jun-29-2021, 04:47 AM
RE: Sum similar items - by deanhystad - Jun-29-2021, 04:51 AM
RE: Sum similar items - by tester_V - Jun-29-2021, 06:58 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python: if 'X' in 'Y' but with two similar strings as 'X' DreamingInsanity 6 3,965 Feb-01-2019, 01:28 PM
Last Post: buran
  Similar to Poker bluekade5050 1 37,824 Nov-14-2018, 04:46 PM
Last Post: j.crater

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020