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()
으로 가장 많이 쓰인 단어를 찾았다.