[Python]Check if any string in a list is contains any string in another list
Question:
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.
e.g.
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.
Answers:
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...
With regex (regular expressions), you can also check each newstitle for tags with
import re
for newstitle in newstitles:
re.search('|'.join(tags), newstitle)`
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.
e.g.
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...
With regex (regular expressions), you can also check each newstitle for tags with
import re
for newstitle in newstitles:
re.search('|'.join(tags), newstitle)`