python - Python程序查找文档列表中是否存在某个关键字(字符串)
问题描述
问题:一位研究人员收集了数千篇新闻文章。但她想将注意力集中在包含特定单词的文章上。
该功能应满足以下条件:
不要包含关键字字符串仅作为较大单词的一部分出现的文档。例如,如果她要查找关键字“关闭”,则您不会包含字符串“封闭”。</p>
她不希望您区分大写字母和小写字母。所以“结案”这句话。当关键字“关闭”时会包含在内</p>
不要让句点或逗号影响匹配的内容。“关门了。” 当关键字为“关闭”时将包含在内。但是你可以假设没有其他类型的标点符号。
我的代码:-
keywords=["casino"]
def multi_word_search(document,keywords):
dic={}
z=[]
for word in document:
i=document.index(word)
token=word.split()
new=[j.rstrip(",.").lower() for j in token]
for k in keywords:
if k.lower() in new:
dic[k]=z.append(i)
else:
dic[k]=[]
return dic
{'casino': [0]}
它必须在给document=['The Learn Python Challenge Casino', 'They bought a car', 'Casinoville?']
,时返回值keywords=['casino']
,但是得到了{'casino': []}
。我想知道是否有人可以帮助我?
解决方案
我将首先使用 split() 标记字符串“new”,然后构建一个集合以加快查找速度。
如果您想要不区分大小写,则需要将两边都小写
for k in keywords:
s = set(new.split())
if k in s:
dic[k] = z.append(i)
else:
dic[k]=[]
return dic
推荐阅读
- java - JavaFX 场景中带有嵌套锚窗格的 KeyEvent
- math - 处理溢出时是否有二进制补码乘法的数学公式?
- python - 如何将多个用户输入保存到 Python tkinter 中的变量中?
- r - 如何根据另一列的条件填充该列的值?
- python - 想为不同的限制为相同的数据集做一个for循环
- javascript - 使用 JS 切换标签内的多个类
- python - 规模大于和小于1的scipy正态分布
- go - 在 Kubernetes 中,当另一个容器正在使用内核时,Go 容器是否会使用所有内核
- python - 做 np.select(condlist,choicelist) 做的事,但只用 pandas
- r - 将 predict() 值中的数据添加到 R 中另一个图的末尾