简体   繁体   中英

[Python]Check if any string in a list is contains any string in another list

I am writing a script for google news.

I get a list of news title and would like to check the title contains any keywords in a list.

eg

newstitle =['Python is awesome', 'apple is tasty', 'Tom cruise has new movie']
tag = ['Python','Orange', 'android']

If any keywords in tag is in the newstitle, I want it to return True value.

I know how to do it with single tag using

any('Python' in x for x in newstitle)

But how to do it with multiple keywords? A if loop is doable but it seems dumb.

Please help. Thanks in advance.

The below code should achieve the required:

any(t in x for x in newstitle for t in tag)

From the docs :

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.

for each newstitle in the list iterate through tag list for tag values in newstitle.

newstitles = ['Python is awesome', 'apple is tasty', 'Tom cruise has new movie']
tags = ['Python', 'Orange', 'android']

for newstitle in newstitles:
   for tag in tags:
      if newstitle.find(tag) != -1:
           #Do your operation...


       

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM