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

2024-03-29 06:42:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要计算文件中第二列的每个实例的数量,如下所示:

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

我试图解决这个问题,但是我的代码显示了输入文件中有多少元素。你知道吗

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])

我需要的输出是: 001 - 3 002 - 2 第003-2页

它只是第二列中特定事件的总和。 我的成绩是7


Tags: 文件csvinimporttxtforaswith
1条回答
网友
1楼 · 发布于 2024-03-29 06:42:03

以下是您需要的:

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)

我想你错过了分隔符。你知道吗

相关问题 更多 >