금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라. 대소문자 구분을 하지 않으며 구두점 또한 무시한다.
- 입력: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
- 출력: "ball"
import collections
import re
from typing import List
class Solution:
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 = collections.Counter(words)
#가장 흔하게 등장하는 단어의 첫 번째 인덱스 리턴
return counts.most_common(1)[0][0]
words = [word for word in re.sub(r'[^\w]',' ', paragraph).lower().split() if word not in banned] counts = collections.Counter(words)
문자가 아닌 모든 것을 공백으로 처리하고 소문자로 나누고 만약 단어가 금지되지 않은 단어라면 카운팅하라는 의미이다.
return counts.most_common(1)[0][0]
그리고 카운팅된 가장 많은 단어를 반환하게 된다.
각 단어들을 대소문자 구분 없이 나눠서 문자열에 저장하는데 같은 단어들이라면 카운팅이 되게 하고 그중 제일 빈도수가 높은 단어를 출력하게 해주는 비교적 쉬운 문제였다.