본문 바로가기
[Language] - Python

# 20. Counter

by Bebsae 2022. 3. 1.

이번 포스트에서는 파이썬의 기본 모듈인 collections 모듈중에서 Counter에 대해 알아볼 것이다.

 

Counter 클래스는 기본적으로 dict(딕셔너리)클래스를 상속받고 있다. 해당 클래스는 요소의 빈도수를 체크하기 적합한 자료형이다. 우선 Counter 클래스를 사용하지 않고 요소의 빈도수를 체크하려면 딕셔너리를 사용할 것이다.

 

corpus = "abcdeabcdabcaba"
d = dict()

for c in corpus:
    d.setdefault(c, 0)
    d[c] += 1
    
d
>>>
{'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1}

위 코드처럼 딕셔너리를 사용하여 각 문자들의 빈도수를 매핑할 수 있다. 하지만, 이는 Counter를 알고있다면 for문이 불필요하게 사용된 코드이다.

 

counter = Counter(corpus)
counter.most_common()
>>>
[('a', 5), ('b', 4), ('c', 3), ('d', 2), ('e', 1)]

counter.most_common(2)
>>>
[('a', 5), ('b', 4)]

Counter 클래스의 most_common() 메소드를 통해 각 문자의 빈도수를 파악할 수 있다. 그리고 인자로 정수를 전달하면 원하는 상위의 빈도수의 문자를 보여주기도 한다.

 

counter2 = Counter({'a': 4, 'b': 2})
counter3 = Counter(a=3, b=2)

counter2.most_common()
>>>
[('a', 4), ('b', 2)]

counter3.most_common()
>>>
[('a', 3), ('b', 2)]

초기화자(__init__())을 보면 알겠지만 다른 방법으로도 빈도수를 체크할 수 있다.

 

for factor in counter.elements():
    print(factor)
    
>>>
a
a
a
a
a
b
b
b
b
c
c
c
d
d
e

elements() 메소드를 사용하여 등록된 요소들을 반환할 수 있다.

 

counter.update('witch')

counter.most_common()
>>>
[('a', 5),
 ('b', 4),
 ('c', 4),
 ('d', 2),
 ('e', 1),
 ('w', 1),
 ('i', 1),
 ('t', 1),
 ('h', 1)]

for c in ('w', 'i', 't', 'h'):
    print(counter[c])
>>>
1
1
1
1

update() 메소드를 통해 새로운 요소들을 추가할 수도 있다.

 

counter.subtract('ait')

counter.most_common()
>>>
[('a', 4),
 ('b', 4),
 ('c', 4),
 ('d', 2),
 ('e', 1),
 ('w', 1),
 ('h', 1),
 ('i', 0),
 ('t', 0)]

subtract() 메소드를 통해 요소들의 빈도수를 1씩 뺄수도 있다. a, i, t가 1씩 줄어든 모습.

 

+ 2022.05.11 추가

Counter 객체에 문자열 단위로 카운팅을 추가하는 방법

https://stackoverflow.com/questions/45340785/update-counter-collection-in-python-with-string-not-letter

 

Update Counter collection in python with string, not letter

How to update a Counter with a string, not the letters of the string? For example, after initializing this counter with two strings: from collections import Counter c = Counter(['black','blue']) ...

stackoverflow.com

 

'[Language] - Python' 카테고리의 다른 글

# 19. [Magic Method] __call__()  (0) 2021.11.19
# 18. 데코레이터 (Decorator)  (0) 2021.11.09
# 17. [Magic Method] __new__() & __init__()  (0) 2021.08.02
# 16. eval  (0) 2021.08.02
# 15. [Tip] chunk  (0) 2021.06.02

댓글