Python
파이썬, 문장에서 단어별 빈도수 카운트 Counter collections
코딩ABC
2024. 11. 19. 17:03
반응형
Counter는 딕셔너리와 유사한 구조로, 키가 항목이고 값이 빈도를 나타냅니다.
단어 카운터
from collections import Counter
text = "apple banana apple cherry banana apple"
word_counts = Counter(text.split())
print(word_counts) # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
(Output)
Counter({'apple': 3, 'banana': 2, 'cherry': 1})
숫자 카운터
from collections import Counter
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
counter = Counter(numbers)
print(counter) # Counter({4: 4, 3: 3, 2: 2, 1: 1})
(Output)
Counter({4: 4, 3: 3, 2: 2, 1: 1})

반응형