Skip to content Skip to sidebar Skip to footer

How To Search For A Keyword In A List Of Strings, And Return That String?

I have a list of strings that are a few words long, and I need to search for two keywords, and return the strings that contain those two key words. I have tried to loop through the

Solution 1:

Try this :

list_ = ["The man walked the dog", "The lady walked the dog","Dogs are cool", "Cats are interesting creatures", "Cats and Dogs was an interesting movie", "The man has a brown dog"]
l1 = [k for k in list_ if 'man' in k and 'dog' in k]

OUTPUT :

['The man walked the dog', 'The man has a brown dog']

Note : Refrain from assigning variable name as list.

Solution 2:

I would use a regex to avoid matchings with words like manifold or dogma:

import re

l = [
    "The man walked the dog", 
    "The lady walked the dog", 
    "Dogs are cool", 
    "Cats are interesting creatures",
    "Cats and Dogs was an interesting movie", 
    "The man has a brown dog",
    "the manner dogma"
]

words = ["man", "dog"]
results = [x for x in l ifall(re.search("\\b{}\\b".format(w), x) for w in words)]
results

>>> ['The man walked the dog', 'The man has a brown dog']

Solution 3:

Try this:

words = ["man", "dog"]
l = ["The man walked the dog", "The lady walked the dog","Dogs are cool", "Cats are interesting creatures", "Cats and Dogs was an interesting movie", "The man has a brown dog"]
new_list = [item for item in l if all((word in item) for word in words)]

gives

['The man walked the dog', 'The man has a brown dog']

(I didn't use the name list since that would mask the built-in type.)

Post a Comment for "How To Search For A Keyword In A List Of Strings, And Return That String?"