【问题标题】:Searching a word in a list在列表中搜索单词
【发布时间】:2021-10-14 01:06:32
【问题描述】:

我正在尝试解决 Kaggle 30 天 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')

【问题讨论】:

  • 从循环中删除 break。否则,它仅在您查找的单词是句子中的第一个单词时才有效(或将 break 放在 if 中)。

标签: python arrays string function


【解决方案1】:

您的程序几乎是正确的。我在for word in sentlist 下方添加了print(),然后意识到每个句子中只检查了第一个单词。然后,您可以发现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

【讨论】:

    【解决方案2】:

    您也可以使用列表推导来减小大小:

    def word_search(doc_list, keyword):
        print([idx for idx, sentence in enumerate(doc_list) if keyword.lower() in sentence.lower()])
    
    word_search(['The Learn Python Challenge Casino', 'They bought a car, and a horse', 'Casinoville?'], 'horse')
    >> [0]
    word_search(['The Learn Python Challenge Casino', 'They bought a car, and a horse', 'Casinoville?'], 'something')
    >> []
    

    【讨论】: