python - 在列表中搜索单词
问题描述
我正在尝试从 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')
解决方案
你的程序几乎是正确的。我在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
推荐阅读
- graphics - 从 3x4 矩阵反投影到世界坐标
- kubernetes - 地形 | 手动编辑 tfstate
- akka - Akka http 请求超时
- html - 制作导航栏的正确方法是什么?
- go - 如何在 Golang 中按索引交换值
- sapui5 - 在类 sap.m.List 中哪里可以找到“项目”聚合?
- c# - 为什么即使我的 C# 代码中没有任何错误,键盘语言编程更改也不会影响?
- java - require_once():javabridge 需要打开失败
- python - 使用 sqlite3 python 到数据库的日期时间
- javascript - 如何在 TUI-Calendar 中禁用设置随机调度顺序