首页 > 解决方案 > 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': []}。我想知道是否有人可以帮助我?

标签: python

解决方案


我将首先使用 split() 标记字符串“new”,然后构建一个集合以加快查找速度。

如果您想要不区分大小写,则需要将两边都小写

for k in keywords:
   s = set(new.split())
   if k in s:
      dic[k] = z.append(i)
   else:
      dic[k]=[]
return dic
   

推荐阅读