Find all matching words from an element of an array, keep those, but delete element's that dont have these words

Viewed 30

I am trying to remove all elements of an array/json that do not have all words from a string in them. For example:

Words to find: World Hold On

Array [
    {
       "title" : "Hold On World",
       "artist": "some guy"
    },
    { 
       "title" : "World, Hold On",
       "artist": "some guy"
    },
    {
       "title" : "World Hold On Now",
       "artist": "some guy"  
    },
    {
       "title" : "World Is Ending",
       "artist": "some guy"
    }
 ]

So with this array, the first three elements should be saved, but the last one should be removed, I have tried something like this:

def removeNonMatches(data, title):
    old = title.split(' ')
    new = '|'.join(old)
    p = re.compile(new, re.I)
    for x in data:
       if bool(p.search(r"\b("+p+")\b", x['title'], re.IGNORECASE)) == False:
            data.remove(x)
    return data

data = [
     {
       "title" : "Hold On World",
       "artist": "some guy"
    },
    { 
       "title" : "World, Hold On",
       "artist": "some guy"
    },
    {
       "title" : "World Hold On Now",
       "artist": "some guy"  
    },
    {
       "title" : "World Is Ending",
       "artist": "some guy"
    }
]

title = 'World Hold On'

new_data = removeNonMatches(data, title)
1 Answers

You may use

data = [
    {
       "title" : "Hold On World",
       "artist": "some guy"
    },
    { 
       "title" : "World, Hold On",
       "artist": "some guy"
    },
    {
       "title" : "World Hold On Now",
       "artist": "some guy"  
    },
    {
       "title" : "World Is Ending",
       "artist": "some guy"
    }
 ]
words = ["World", "Hold", "On"]

keep =  [item for item in data
         if all(word in item["title"] for word in words)]
print(keep)

Which yields

[{'title': 'Hold On World', 'artist': 'some guy'}, 
 {'title': 'World, Hold On', 'artist': 'some guy'}, 
 {'title': 'World Hold On Now', 'artist': 'some guy'}]


To even have upper- and lowercase words, use

words = ["world", "hold", "on"]
keep =  [item for item in data
         if all(word in item["title"].lower() for word in words)]
Related