비버놀로지

[나이브 베이즈 분류] Bag of Words 본문

인공지능 머신러닝

[나이브 베이즈 분류] Bag of Words

KUNDUZ 2022. 11. 3. 09:29
728x90

Bag of Words

Bag of Words 모델을 직접 구현하겠습니다.

create_BOW() 함수를 완성하세요. create_BOW()는 문장 한 줄을 입력 받고 해당 문장의 단어 사전과 Bag of Words 모델을 순서대로 리턴합니다.

>>> sentence = "Bag-of-Words 모델을 Python으로 직접 구현하겠습니다."
>>> create_BOW(sentence)
{'bag': 1, 'of': 1, 'words': 1, '모델을': 1, 'Python으로': 1, '직접': 1, '구현하겠습니다': 1}
 

실습

create_BOW() 함수의 조건은 다음과 같습니다.

  1. 단어는 모두 소문자로 치환되어야 합니다. .lower()을 사용하세요.
  2. 특수문자를 모두 제거합니다.
    정규식표현(re)이 사용된 remove_special_characters() 함수를 이용하세요.
  3. 단어는 space 를 기준으로 잘라내어 만듭니다. split()을 사용하세요.
  4. 단어는 한 글자 이상이어야 합니다. 단어의 길이를 체크하기 위해 len()을 사용하세요.

Tips!

딕셔너리의 개념을 예제를 통해 다시 한 번 떠올려볼까요? 딕셔너리는 key와 value로 이루어진 자료형입니다.

my_dict = {'name':'Michael', 'age':10}

위 코드에서 my_dict['age']의 결과는 10입니다. 이때 'age'라는 key로 10이라는 value를 꺼낸 것입니다.

 

 

import re

special_chars_remover = re.compile("[^\w'|_]")

def main():
    sentence = input()
    bow = create_BOW(sentence)

    print(bow)


def create_BOW(sentence):
    sentence = sentence.lower()
    
    sentence = remove_special_characters(sentence)
    
    sentence = sentence.split()
    
    print(sentence)
    
    bow = {}
    
    for s in sentence:
        if s in bow:
            bow[s] +=1
        else:
            bow[s] = 1
    
    print(bow)
    
    return bow


def remove_special_characters(sentence):
    return special_chars_remover.sub(' ', sentence)


if __name__ == "__main__":
    main()

 

 

728x90
Comments