본문 바로가기

파이썬

[파이썬] 키워드를 리스트 안에서 검색하기

#내가 짠 답
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