Algorithm/python 구현

algorithm(python), 단어빈도수 세는 프로그램

euncheol kim 2022. 1. 15. 17:10

goal

단어빈도수를 세어주는 코드를 이해한다
1] 기본 dictionary의 활용 3개
2] defaultdic을 이용한 방법 1개

게시글에 오류, 수정, 추가, 개선이 필요할 경우 지적해주시면 감사하겠습니다.


단어빈도수 세는 프로그래밍 (dictionary이용 3가지 방법)

[1] 기본 dictionary의 활용 3개

  1. 기본적인 dictionary 이용
  2. dictionary + try~exception 이용
  3. dictionary.get 이용

[2] defaultdic을 이용한 방법 1개


[1] 기본 dictionary의 활용 3개

[1-1] 코드내용

document = ["apple", "apple", # 2개
            "banana", "banana", "banana", "banana", # 4개
            "orange", "orange", "orange", # 3개
            "coke","coke","coke","coke","coke","coke","coke", #7개
            "location", "location", # 2개
            "man", "man", "man", "man", "man" # 5개
            ]


# [1번] -> 기본적인 dictionary 이용
word_count = {}
for word in document :
    if word in word_count :
        word_count[word] += 1
    else :
        word_count[word] = 1 
print("[1번] : ", word_count)

#[2번] -> dictionary + try~exception 이용
word_count = {}
for word in document :
    try :
        word_count[word] += 1
    except KeyError:
        word_count[word] = 1
print("[2번] : ", word_count)

#[3번] -> dictionary.get()이용
word_count = {}
for word in document :
    previous_count = word_count.get(word, 0)
    word_count[word] = previous_count + 1
print("[3번] : ", word_count)

[1-2] 출력내용

[1-3] 코드설명

  1. 기본적인 dictionary이용
  2. dictionary + try~exception 이용
    • (try문) : 만약, word_count에 word가 있으면 1을 더해준다.
    • (exception문) : 만약, word_count에 word에 해당하는 key값이 없으면 1을 대입해준다.
  3. dictionary.get()
    • word_count.get()을 이용하여 key에 해당하는 value를 previous_count에 넣어준다.
      • word_count.get()의 return은 key가 존재하면 key에 해당하는 value를 넣어준다.
      • 만약, key값이 존재하지 않으면 사용자가 초기화하고 싶은 값을 넣어 dictionary에 key와 value를 저장한다.
    • previous_count에 1을 더하여 단어빈도수 1을 증가시킨다.

[2] defaultdic을 이용한 방법 1개

[2-1] 코드내용

from collections import defaultdict

document = ["apple", "apple", # 2개
            "banana", "banana", "banana", "banana", # 4개
            "orange", "orange", "orange", # 3개
            "coke","coke","coke","coke","coke","coke","coke", #7개
            "location", "location", # 2개
            "man", "man", "man", "man", "man" # 5개
            ]

word_counts = defaultdict(int) # word_counts에 존재하지 않는 key를 받을 때 vaule는 0을 갖는다.
for word in document :
    word_counts[word] += 1
print("defaultdic : ", word_counts)

[2-2] 출력내용

[2-3] 코드설명

  • 1행 : collections 모듈에서 defaultdict를 불러온다.
  • 11행 : word_counts를 defaultdic(int)로 생성하고 word_counts가 key값을 받을 때 초기값은 0을 갖는다.