#내가 짠 답
def word_search(doc_list, keyword):
"""
Takes a list of documents (each document is a string) and a keyword.
Returns list of the index values into the original list for all documents
containing the keyword.
Example:
doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"]
>>> word_search(doc_list, 'casino')
>>> [0]
"""
ids=[]
for i in doc_list:
bucket = i.split(' ')
for j in bucket:
j = j.lower().strip(',').strip('?').strip('.')
if j == keyword:
ids.append(doc_list.index(i))
return list(set(ids))
#Solution(권장답안)
def word_search(doc_list, keyword):
# list to hold the indices of matching documents
indices = []
# Iterate through the indices (i) and elements (doc) of documents
for i, doc in enumerate(doc_list):
# Split the string doc into a list of words (according to whitespace)
tokens = doc.split()
# Make a transformed list where we 'normalize' each word to facilitate matching.
# Periods and commas are removed from the end of each word, and it's set to all lowercase.
normalized = [token.rstrip('.,').lower() for token in tokens]
# Is there a match? If so, update the list of matching indices.
if keyword.lower() in normalized:
indices.append(i)
return indices
https://www.kaggle.com/code/colinmorris/strings-and-dictionaries
Strings and Dictionaries
Explore and run machine learning code with Kaggle Notebooks | Using data from No attached data sources
www.kaggle.com
'파이썬' 카테고리의 다른 글
[판다스] 시리즈 만드는 법: 리스트 이용해서 간단하게 (0) | 2024.01.20 |
---|---|
[판다스] 데이터프레임을 만드는 다양한 방법과 컬럼명 지정하기 (0) | 2024.01.20 |
[판다스] pandas.set_option error 옛 코드를 돌리다가 오류 났을 때 (0) | 2024.01.20 |
[파이썬] any()와 List Comprehension (0) | 2024.01.17 |
[파이썬] 불리언 연산 순서 (0) | 2024.01.16 |