금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라. 대소문자 구분을 하지 않으며, 구두점(마침표, 쉼표 등) 또한 무시한다.
일단 콤마나 다른 값들을 없애는 방법이 있다면, 정규표현식이 있다.
words = [word for word in re.sub(r'[^\\w]', ' ', paragraph).lower()
.split() if word not in banned]
정규식에서 \w는 단어 문자(Word Character)를 뜻하며, ^은 not을 의미한다. 따라서 위 정규식 단어는 문자가 아닌 모든 문자를 공배긍로 치환하는 역할을 한다.
리스트 컴프리헨션의 조건절에는 banned에 포함되지 않능 단어만을 대상으로 한다.
import collections
import re
def most_common_word(paragraph: str, banned: list[str]) -> str:
words = [word for word in re.sub(r'[^\\w]', ' ', paragraph)
.lower().split() if word not in banned]
counts = collections.defaultdict(int)
for word in words:
counts[word] += 1
return max(counts, key=counts.get)
if __name__ == '__main__':
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
print(most_common_word(paragraph, banned))
collection defautldic 디셔너리와 거의 비슷하지만 key값이 없을 경우 미리 저징하네요.