본문 바로가기

PYTHON

[python3 | 알고리즘] 14. 문자열 조작(가장 흔한 단어)

728x90
반응형
[조건]

1) 금지 단어를 제외한 가장 흔하게 등장하는 단어 출력
2) 대소문자 구분 X
3) 구두점(쉼표, 마침표 등) 무시


[입력]

paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]


[출력]

"ball"

 

 

1. 리스트 컴프리헨션, Counter 객체 사용

 

 - 전처리 작업 필요

 - 정규식 사용

 

 * 정규식

  1) \w ==> 단어 문자를 뜻함

  2) ^ ==> not

  

#Counter 객체 사용 X

def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
    words = [word for word in re.sub(r'[^\w]', ' ', paragraph).lower().split() if word not in banned]

    #counts 는 딕셔너리 변수
    counts = collections.defaultdict(int)
    for word in words:
        counts[word] += 1

    #가장 흔하게 등장하는 단어의 첫 번째 인덱스 리턴
    return counts.most_common(1)[0][0]


#Counter 객체 사용 O

def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
    words = [word for word in re.sub(r'[^\w]', ' ', paragraph).lower().split() if word not in banned]
    
    #counts 는 딕셔너리 변수
    counts = collections.Counter(words)

    #가장 흔하게 등장하는 단어의 첫 번째 인덱스 리턴
    # most_common(1) ==> [('ball', 2)]
    return counts.most_common(1)[0][0]

728x90
반응형