Counter 사용하기

Tasker_Jang·2026년 3월 30일

1. 기본 개념 — Counter

Counter는 Python 표준 라이브러리 collections 모듈에 포함된 클래스입니다. 리스트나 이터러블에서 각 항목이 몇 번 등장했는지 자동으로 세주는 딕셔너리입니다.

from collections import Counter

2. 기본 사용법

from collections import Counter

lines = ["두산밥캣", "영업이익", "두산밥캣", "두산밥캣", "영업이익"]

counts = Counter(lines)
print(counts)
# Counter({'두산밥캣': 3, '영업이익': 2})

딕셔너리처럼 키로 접근할 수 있습니다.

counts["두산밥캣"]  # 3
counts["영업이익"]  # 2
counts["없는항목"]  # 0 (KeyError 대신 0 반환 — 일반 dict와의 차이)

3. Counter를 쓰지 않으면

직접 구현하면 이렇게 해야 합니다.

counts = {}
for ln in lines:
    counts[ln] = counts.get(ln, 0) + 1

Counter가 이걸 한 줄로 해결합니다.


4. 자주 쓰는 메서드

counts = Counter(["A", "B", "A", "C", "A", "B"])

# 가장 많이 등장한 항목 상위 N개
counts.most_common(2)
# [('A', 3), ('B', 2)]

# 전체 항목 수 (중복 포함)
sum(counts.values())
# 6

# 특정 횟수 이상 등장한 항목만 필터링
noise = {item for item, cnt in counts.items() if cnt >= 2}
# {'A', 'B'}

5. 핵심 요약

기능코드
카운팅Counter(iterable)
항목 조회counts["키"] (없으면 0)
상위 N개counts.most_common(N)
필터링{k for k, v in counts.items() if v >= N}

한 줄 요약: Counter는 항목별 등장 횟수를 자동으로 세주는 딕셔너리로, 전처리 과정에서 반복 헤더·타이틀 등 노이즈 라인을 감지할 때 핵심적으로 사용됩니다.

profile
ML Engineer 🧠 | AI 모델 개발과 최적화 경험을 기록하며 성장하는 개발자 🚀 The light that burns twice as bright burns half as long ✨

0개의 댓글