简体   繁体   中英

How to count the number of occurrences in code?

I need to count number of each instance for second column in file that looks like this:

1234;'001';X
1234;'001';X
1234;'003';Y
1280;'001';X
1280;'002';Y
1280;'002';Y
1280;'003';X

I tried to solve the problem, but my code shows how many elements are in the input file.

import csv
from collections import Counter

#get line
with open('myFile.txt', 'r') as file:
    next(file) #skip header
        occurrence = Counter(tuple(row[1:2]) for row in csv.reader(file))
print(occurrence)



with open('myOutputFile.txt', 'w') as file2:
writer = csv.writer(file2)
writer.writerow(['Nr powiatu: ' 'Wystapienia: '])
for occur, count in occurrence.items():
    writer.writerow([occur, count])

The output I need is: 001 - 3 002 - 2 003 - 2

It's just the sum of specific occurrences in second column. And my result is 7

Here is what you need:

import csv
from collections import Counter

with open('myFile.txt', 'r') as fd:
    next(fd)
    occurrence = Counter([row[1] for row in csv.reader(fd, delimiter=';')])
print(occurrence)

I think you are missing the delimiter.

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