문자열 리스트에서 가장 자주 등장하는 단어를 찾아야 할 때는 리스트를 순회하면서 max 메서드를 활용해 가장 높은 빈도를 가진 단어를 손쉽게 구할 수 있습니다. 이번 글에서는 collections 모듈의 defaultdict를 사용해 단어별 빈도를 계산하고, 그중 최빈 단어를 추출하는 방법을 알아보겠습니다.
예제
다음은 전체 동작 과정을 보여주는 예시입니다.
from collections import defaultdict
my_list = ["python is best for coders", "python is fun", "python is easy to learn"]
print("The list is :")
print(my_list)
my_temp = defaultdict(int)
for sub in my_list:
for word in sub.split():
my_temp[word] += 1
result = max(my_temp, key=my_temp.get)
print("The word that has the maximum frequency :")
print(result)
출력 결과
The list is :
['python is best for coders', 'python is fun', 'python is easy to learn']
The word that has the maximum frequency :
python
동작 원리 설명
필요한 패키지(
defaultdict)를 환경에 임포트합니다.문자열로 이루어진 리스트를 정의하고 콘솔에 출력합니다.
정수형 값을 저장하는 딕셔너리를 생성해 변수에 할당합니다.
defaultdict(int)는 존재하지 않는 키에 접근할 때 자동으로 0으로 초기화해 주므로 빈도 계산에 매우 편리합니다.문자열 리스트를 순회하면서 각 문장을 공백을 기준으로 분할합니다.
분할된 모든 단어의 등장 횟수(빈도)를 하나씩 증가시키며 계산합니다.
max메서드에key=my_temp.get을 지정해 값(빈도)이 가장 큰 키, 즉 가장 자주 등장한 단어를 찾습니다.결과를 변수에 할당한 뒤 콘솔에 출력합니다.
참고: Counter를 사용한 더 간단한 방법
파이썬에서는 collections.Counter를 사용하면 같은 작업을 더욱 간결하게 처리할 수 있습니다.
from collections import Counter
my_list = ["python is best for coders", "python is fun", "python is easy to learn"]
words = []
for sub in my_list:
words.extend(sub.split())
result = Counter(words).most_common(1)[0][0]
print(result) # python
두 방법 모두 시간 복잡도는 O(N)(N은 전체 단어 수)으로 효율적이며, 상황에 따라 선호하는 방식을 선택해 사용하면 됩니다.