728x90
반응형
[조건]
1) 금지 단어를 제외한 가장 흔하게 등장하는 단어 출력
2) 대소문자 구분 X
3) 구두점(쉼표, 마침표 등) 무시
[입력]
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
[출력]
"ball"
1. 리스트 컴프리헨션, Counter 객체 사용
- 전처리 작업 필요
- 정규식 사용
* 정규식
1) \w ==> 단어 문자를 뜻함
2) ^ ==> not
#Counter 객체 사용 X
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 는 딕셔너리 변수
counts = collections.defaultdict(int)
for word in words:
counts[word] += 1
#가장 흔하게 등장하는 단어의 첫 번째 인덱스 리턴
return counts.most_common(1)[0][0]
#Counter 객체 사용 O
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 는 딕셔너리 변수
counts = collections.Counter(words)
#가장 흔하게 등장하는 단어의 첫 번째 인덱스 리턴
# most_common(1) ==> [('ball', 2)]
return counts.most_common(1)[0][0]
728x90
반응형
'PYTHON' 카테고리의 다른 글
[python3] spring SQL log 파라미터 치환해서 추출하기. (0) | 2021.04.13 |
---|---|
[python3 | 알고리즘] 15. 문자열 조작(그룹 애너그램) (0) | 2021.03.09 |
[python3 | 알고리즘] 13. 문자열 조작(로그파일 재정렬) (0) | 2021.03.09 |
[python3 | 알고리즘] 12. 문자열 조작(문자열 뒤집기) (0) | 2021.03.09 |
[python3 | 알고리즘] 11. 문자열 조작(팰린드롬) (0) | 2021.03.08 |