2

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

e.g.

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

If any keywords in tag are in newstitle, I want it to return True.

I know how to do it with a single tag using:

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

But how to do it with multiple keywords?

Jonny
  • 3,807
  • 8
  • 31
  • 48
Max Cheung
  • 176
  • 3
  • 13

3 Answers3

5

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.

rok
  • 9,403
  • 17
  • 70
  • 126
0

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...


       
Alex
  • 1
  • 1
0

With regex (regular expressions), you can also check each newstitle for tags with

import re
for newstitle in newstitles:
    re.search('|'.join(tags), newstitle)`
Christabella Irwanto
  • 1,161
  • 11
  • 15