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

Python 如何计算代码中出现的次数?,python,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(f

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

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,这是你需要的:

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)
我认为您缺少分隔符。

以下是您需要的:

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)

我认为您缺少分隔符。

使用该示例运行代码会为我打印:
计数器({'001':3,'003':2,'002':2})
。不幸的是,我只得到了:Nr poviatu:wystapiena:(),6总之,Convergabot帮了我的忙。它工作得很好——正如我所希望的那样。(很抱歉代码中的这些波兰语单词--“Nr Poviatu:”Wystapiena:”。我完全忘记了它们,对于阅读代码的外国人来说,这可能看起来很奇怪和不可理解。)使用该示例运行代码会打印:
计数器({'001':3,'003':2,'002':2})
给我。不幸的是,我只得到了:Nr Poviatu:Wystapiena:(),6,他帮了我的忙。它工作得很好——正如我所希望的那样。(很抱歉代码中的这些波兰语单词——“Nr Poviatu:”“Wystapienia:”。我完全忘了它们,外国人读代码时可能会觉得奇怪和难以理解。)不过,
lst=[]
是不需要的。你太棒了!谢谢你的困惑和不倦:)不过不需要
lst=[]
。你太棒了!谢谢你和多年生的诺布:)