该代码显示字符串列表包含一个特定的单词。请告诉我为什么我的代码没有给出正确的答案?

问题描述 投票:-1回答:2

def word_search(doc_list,关键字):“”获取文档列表(每个文档是一个字符串)和一个关键字。将所有文档的索引值列表返回到原始列表包含关键字。

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

for i,doc in enumerate(doc_list):
    l=[i for j in doc.split() if j.rstrip('.,').lower()==keyword.lower()]

return l
python string list search list-comprehension
2个回答
0
投票
此函数将为您返回带有字符串项目中关键字的项目索引的列表。

doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"] def word_search(doc_list, keyword): return [i for i, v in enumerate(doc_list) if v.lower().find(keyword.lower()) > -1] word_search(doc_list, 'casino')

返回索引

[0, 2]


0
投票
您可以执行以下操作:

def word_search(doc_list, keyword): l=[] for i,doc in enumerate(doc_list): l.append([i for j in doc.split() if j.rstrip('.,').lower()==keyword.lower()]) return l doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"] match=word_search(doc_list, 'casino') print(match)

搜索不会返回Casinoville的索引,因为它不是一个单独的单词
© www.soinside.com 2019 - 2024. All rights reserved.