Python: 在列表中搜索给出 TypeError

Python: search in a list give TypeError

你们能帮我看看下面这些代码吗?当把所有东西放在一起时,我得到了 TypeError: 'builtin_function_or_method' object is not subscriptable。我已经尝试 运行 单独编写较小的代码段,但我工作得很好:

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]
    """
    result = []
    for i in range (len(doc_list)-1):
        if keyword.lower() in doc_list[i].lower().rstrip(".,").split():
            result.append[i]
    return result

Error: TypeError: 'builtin_function_or_method' object is not subscriptable

单独的代码段运行好吧:

doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"]
new_list = doc_list[0].lower().rstrip(".,").split()
print(new_list)

result.append[i] 更新了 result.append(i),因为 append 是一种方法:

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]
    """
    result = []
    for i in range (len(doc_list)-1):
        print(i)
        if keyword.lower() in doc_list[i].lower().rstrip(".,").split():
            result.append(i)
    return result

doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"]
print(word_search(doc_list, 'casino'))

.append是列表的内置函数。

 result.append[i]

您正在尝试从“函数”中获取第 i 个元素。因此它显示错误。

你真的想要

result.append(i)
result = []
for i in range (len(doc_list)-1):
    if keyword.lower() in doc_list[i].lower().rstrip(".,").split():
        result.append(i)
return result

我已经更新了代码如下所示 请调整到您满意的程度

      def word_search(doc_list, keyword):
            result = [ ]
            for i in range(len(doc_list) - 1):
                if keyword.lower() in doc[i].lower().rstrip('.,').split():
                      result.append(doc[i])
            print(result)

我们是否应该创建列表并对其进行测试,这就是您将得到的结果

输入:

      doc_list = ['The Learn Python Challenge Casino.', 'They bought a car', 'Casinoville']

      word_search(doc_list, 'Casino')

输出:

       ['The Learn Python Challenge Casino']