简体   繁体   English

如何计算代码中的出现次数?

[英]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 我需要的输出是:001-3002-2003-2

It's just the sum of specific occurrences in second column. 这只是第二列中特定事件的总和。 And my result is 7 我的结果是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. 我认为您缺少分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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