[Python] Most Common Word - 819LeetCode

찐새·2022년 6월 22일
0

코딩테스트

목록 보기
15/53
post-thumbnail

819. Most Common Word

풀이

import re
from collections import Counter

def mostCommonWord(paragraph, banned):
    p = re.sub("[^\w]", " ", paragraph.lower())
    string = [word for word in p.split() if word not in banned]
    c = Counter(string).most_common()
    return c[0][0]

정규식인 re.sub(정규식, 바꿀 문자, 문자열)을 이용해 풀었다. \w단어 문자(Word Character)를 뜻하며, [^\w]단어 문자가 아닌 모든 문자를 의미한다.

문자열에서 단어 문자가 아닌 모든 문자를 공백으로 치환 후 리스트 컴프리헨션으로 banned에 속하지 않은 단어를 걸러냈다. Counter(리스트).most_common()으로 가장 많이 쓰인 단어를 찾았다.

profile
프론트엔드 개발자가 되고 싶다

0개의 댓글