Paras Ghai
Paras Ghai

Reputation: 373

Logic to find if words are present in text in python

I have a string and a list of words which i want to check in case those are present in given text string . I am using the below logic.....is there any other way to optimize it :-

import re
text="""
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make
it very attractive for Rapid Application Development"""
tokens_text=re.split(" ",text)
list_words=["programming","Application"]
if (len(set(list_words).intersection(set(tokens_text)))==len(list_words)):
    print("Match_Found")

Upvotes: 1

Views: 109

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

With set.issubset(other) operation:

text="""
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make
it very attractive for Rapid Application Development"""
tokens = text.split()
list_words = ["programming", "Application"]

if (set(list_words).issubset(set(tokens))):
    print("Match_Found")

Or simply with all function:

if all(x in tokens for x in list_words):
    print("Match_Found")

Upvotes: 1

Nico Bleiler
Nico Bleiler

Reputation: 493

You can use python’s in operator, i do not know if it is faster.

str = "Messi is the best soccer player"

"soccer" in str
-> True

"football" in str
-> False

Upvotes: 0

Related Questions