foreword
A few days ago, I saw a person asking a question in the group, and I wrote down the question at that time, as shown in the figure below.
It doesn't look very difficult. This sample code seems to have no problem with logic or anything, but the result output is something wrong. The reason is that because the title is a list, not a string, it needs to add another layer of extraction.
1. Solution
Here are two methods for everyone to learn and reference. Of course, there must be other methods. You are welcome to actively try.
Method 1: Regular reading
This method is similar to the logic in the example code, except that the list is fetched one more time, and the specific elements in the list are obtained, and the result is obtained.
# -*- coding: utf-8 -*-
# 方法一
keywordlist = ['python', '应用']
title = [['人生苦短,我应用python'], ['Rick Xiang 666'], ['歪歪nb'], ['为才哥打call'], ['网络爬虫的应用']]
for luwen in title:
if keywordlist[0] in luwen[0] and keywordlist[1] in luwen[0]:
print(luwen)
After running, the code results are as follows:
Method 2: Use the operator library
This method is provided by Cai Ge or whoever provides it, and it can also meet the requirements.
# -*- coding: utf-8 -*-
import operator
keywordlist = ['python', '应用']
title = [['人生苦短,我应用python'], ['Rick Xiang 666'], ['歪歪nb'], ['为才哥打call'], ['网络爬虫的应用'], ['python爬虫与数据挖掘']]
for luwen in title:
if operator.contains(luwen[0], keywordlist[0]) and operator.contains(luwen[0], keywordlist[1]):
print(luwen)
After running, the result is shown in the following figure:
Some friends may ask, if the title requires keywords to be kept, otherwise it will be deleted from the list. I really did not do this operation here, but I feel that the obtained value is returned and taken directly in the hand. As for The subsequent processing is unknown. If you are really interested, here is also an idea, you can go to the corresponding search index value in the list, save the found index, and then delete the index that is not found.
3. Summary
In this paper, two solutions are given for the keyword inclusion problem of lists. Although the article exemplifies two methods, the editor believes that there must be other methods, and everyone is welcome to advise in the comment area.
Little friends, hurry up and practice it!