首页 > 解决方案 > 在列表中搜索单词

问题描述

我正在尝试从 Kaggle 30 Days of ML 课程中解决以下问题。但是输出是一个空列表,我做错了什么?提前致谢。

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]
    """
    sentence_lst = []
    for sent in doc_list:
        l = sent.split(' ')
        sentence_lst.append(l)
        
    i_lst = []
    for i, sentlist in enumerate(sentence_lst):
        for word in sentlist:
            if str(word) == str(keyword):
                i_lst.append(i)
            break
    return i_lst
                
                
# Check your answer
# q2.check()
word_search(['The Learn Python Challenge Casino', 'They bought a car, and a horse', 'Casinoville?'],'horse')

标签: pythonarraysstringfunction

解决方案


你的程序几乎是正确的。我在print()下面添加了一个for word in sentlist,然后意识到每个句子中只检查了第一个单词。然后,你可以发现break是放错地方了,应该是在if语句中。

尝试这个:

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]
    """
    sentence_lst = []
    for sent in doc_list:
        l = sent.split(' ')
        sentence_lst.append(l)
    print(sentence_lst)
    i_lst = []
    for i, sentlist in enumerate(sentence_lst):
        for word in sentlist:
            if str(word) == str(keyword):
                i_lst.append(i)
                break
    return i_lst

推荐阅读