Most Common Word [ 많이 쓰인 단어 밴 당한 단어 제외 ]
python3
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]코드를 입력하세요
[문제해결]
[참고사이트]
https://ponyozzang.tistory.com/335
정규 표현식을 사용하여 문자열을 치환
[참고사이트]
https://docs.python.org/ko/3/library/collections.html#collections.Counter
(1) Counter 객체(collections.Counter)
편리하고 빠르게 개수를 세도록 지원하는 계수기 도구
[참고]
(2) most_common(n)
n 개의 가장 흔한 요소와 그 개수를 가장 흔한 것부터 가장 적은 것 순으로 나열한 리스트를 반환합니다. n이 생략되거나 None이면, most_common()은 계수기의 모든 요소를 반환합니다. 개수가 같은 요소는 처음 발견된 순서를 유지합니다
collections.Counter(words).most_common(1)[0][0]
python3
class Solution: def tokenizer(self,paragraph): punctuations = "[!?',;. ]+" return re.split(punctuations, paragraph)
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
paragraph=self.tokenizer(paragraph.lower())
counter = {}
for word in paragraph:
if word in banned:
continue
if word in counter.keys():
counter[word] += 1
else:
counter[word] = 1
return max(counter.items(), key=lambda x: x[1])[0]
알고리즘 단계는 4단계다
(1)문자열을 소문자로 만들고,
(2)특수문자 빼버리고,
(3)딕셔너리에다가 밴되지 않은 단어를 넣은 갯수를 만들고,
(4)갯수를 센다.
[keys 함수 참고]
https://www.tutorialspoint.com/python3/dictionary_keys.htm
[이 문제에 대한 다른 블로거의 해결방법 ]
https://ywtechit.tistory.com/37
#### **가장 흔한 단어라 빅데이터를 쓰는데 있어서 나름 중요한 알고리즘 같다.**