Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

JustDoEat

[Python/String-Manipulation] Most Common Word 본문

카테고리 없음

[Python/String-Manipulation] Most Common Word

kingmusung 2023. 11. 22. 22:14

문제.

주어진 문자열 paragraph과 금지된 단어들의 문자열 배열 banned이 있습니다. 금지된 단어가 아닌 가장 빈번하게 나타나는 단어를 반환하세요. 적어도 하나의 금지되지 않은 단어가 있으며, 답은 유일함이 보장됩니다.
paragraph에 포함된 단어들은 대소문자를 구분하지 않으며, 답은 소문자로 반환되어야 합니다.

 

코드.

def find_value(count_words ,value )->list:
    many_word=[]
    for keys,values in count_words.items():
        if values == value:
            many_word.append(keys)

    return many_word


str_input = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]

# 알파벳과 숫자만 남기기
filtered_words = [''.join(char.lower() for char in word if char.isalnum()) for word in str_input.split()]
#리스트 컴프리핸션을 사용해서, for word in str_input.split() 단어 갯수만큼 일단 반복, for char in word 단어의 알파벳갯수만큼 반복하다 if char.isalnum() 해당하면
#char.lower() 소문자로 바꾸고 ''.join 조인해주기
"""
 filtered_word = ''
for char in str_input:
    if char.isalnum():
        filtered_word += char
    elif not char.isalnum():
        filtered_word += ' '
        
"""

print(filtered_words)

count_words={}

for word in filtered_words: #단어 단위로 쪼갠 후 사전에 해당 단어가 있으면, 단어를 키값 빈도수를 벨류값으로
    if word in count_words:
        count_words[word]+=1

    elif word not in count_words and word not in banned:
        count_words[word]=1

max = -1

for keys,value in count_words.items():
    if max<=value:
        max = value    

print(find_value(count_words,max))

 

느낀점.

리스트컴프리핸션을 쓰면 코드가 매우 간결해지므로 잘 이용해야겠고, 안에 조건이 길어질수록 주석처리해놓은 맨트처럼 차근차근 적은다음에 최종적으로 완성을 하는게 가장 좋은 방법 같다.

#리스트 컴프리핸션을 사용해서, for word in str_input.split() 단어 갯수만큼 일단 반복, for char in word 단어의 알파벳갯수만큼 반복하다 if char.isalnum() 해당하면

#char.lower() 소문자로 바꾸고 ''.join 조인해주기