Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用循环筛选包含关键字列表的字符串列表_Python_String_List - Fatal编程技术网

Python 使用循环筛选包含关键字列表的字符串列表

Python 使用循环筛选包含关键字列表的字符串列表,python,string,list,Python,String,List,我有一个包含字符串的列表,其中包含文本体中的描述,如下所示: stringlist = ['I have a dog and cat and the dog is seven years old', 'that dog is old'] 我需要通过另一个列表中的关键字列表过滤这些字符串: keywords = ['dog', 'cat', 'old'] 以及根据关键字在字符串中的定位次数将其追加到行中 filteredlist = [['dog', 'dog', 'cat', 'old'],

我有一个包含字符串的列表,其中包含文本体中的描述,如下所示:

stringlist = ['I have a dog and cat and the dog is seven years old', 'that dog is old']
我需要通过另一个列表中的关键字列表过滤这些字符串:

keywords = ['dog', 'cat', 'old']
以及根据关键字在字符串中的定位次数将其追加到行中

filteredlist = [['dog', 'dog', 'cat', 'old'], ['dog', 'old']]
我在stringslist中拆分字符串,并使用列表理解来检查关键字是否在列表中,但在循环遍历关键字时没有正确输出

当我使用一个特定字符串进行搜索时,代码正在运行,如下所示:

filteritem = 'dog'
filteredlist = []
for string in stringlist:
    string = string.split()
    res = [x for x in string if filteritem in x]
    filteredlist.append(res)
filteredlist = [['dog', 'dog'], ['dog']]
生成的filteredlist如下所示:

filteritem = 'dog'
filteredlist = []
for string in stringlist:
    string = string.split()
    res = [x for x in string if filteritem in x]
    filteredlist.append(res)
filteredlist = [['dog', 'dog'], ['dog']]
它为关键字位于字符串序列中的每个实例追加关键字

当我尝试使用for循环遍历关键字列表(如下所示)时,输出将丢失结构

filteredlist = []
for string in stringlist:
    string = string.split()
    for keyword in keywords:
        res = [x for x in string if keyword in x]
        filteredlist.append(res)
以下是输出:

filteredlist =  [['dog', 'dog'], ['cat'], ['old'], [], ['dog'], [], ['old'], []]

我认为我在处理这个问题时完全错了,所以任何其他方法或解决方案都会有所帮助。

您可以将其作为嵌套列表编写

>>> [[word for word in string.split() if word in keywords] for string in stringlist]
[['dog', 'cat', 'dog', 'old'], ['dog', 'old']]

我不太清楚你的问题是什么。
filtered\u列表
是否高于您想要的输出外观?顶部的filteredlist是我想要的输出外观。请点击:)您可以使用
集合
。谢谢!知道那里一定有一个嵌套的列表。