0

I have a list of lists in which I want to return the contents of strings within each list that match specific keywords.

THIS IS ORIGINAL LIST:

list_orig = [['summary of the', 'cold weather', 'bother me over high'], ['what is in a name?', 'reveals a lot', 'juniper relationship']]

WANT TO APPLY THIS KEYWORD SEARCH:

keywords = ['summary', 'indicates','suggesting', 'relationship', 'reveals']

RESULT DESIRED:

list_refine = [['summary of the'], ['reveals a lot', 'juniper relationship']]

So far, i have the code to apply to a single list but I don't know how to look that over all the lists. HERE IS CODE FOR ONE LIST:

string1 = list_orig
substr1 = keywords

def Filter(string, substr): 
    return [str for str in string if
             any(sub in str for sub in substr)] 

print(Filter(string1, substr1))

HERE IS RESULT FOR 1 LIST:

['summary of the']

I researched so many ways to loop over the lists of lists. Here is 1 attempt.

for item in string3:
     new.append([])
     for item in items:
        item = Filter(string1, substr1)
        new[-1].append(item)
item

just got a blank list Thanks everyone! Appreciate it :)

2 Answers 2

1

You can use a for loop to iterate over the list and another for loop to iterate over the items and keywords like this,

list_orig = [['summary of the', 'cold weather', 'bother me over high'], ['what is in a name?', 'reveals a lot', 'juniper relationship']]

keywords = ['summary', 'indicates','suggesting', 'relationship', 'reveals']

list_refine = []

for l_inner in list_orig:
    l_out = []
    for item in l_inner:
        for word in keywords:
            if word in item:
                l_out.append(item)
    list_refine.append(l_out)
print(list_refine) # [['summary of the'], ['reveals a lot', 'juniper relationship']]
Sign up to request clarification or add additional context in comments.

2 Comments

I spent so long on this...thanks so much again Sreeram...you're awesome!
is there a way to append an empty list if the word doesn't exist so I still have the same number of lists with the list eg. [['summary of the'], []] if i was only searching for the word summary...thanks!
0

Here is an alternative solution without explicit loops

list_orig = [['summary of the', 'cold weather', 'bother me over high'], ['what is in a name?', 'reveals a lot', 'juniper relationship']]

def contains_keyword(sentence):
    keywords = ['summary', 'indicates','suggesting', 'relationship', 'reveals']
    return any([(kw in sentence) for kw in keywords])

list_refine = [
    (sentence for sentence in lst if contains_keyword(sentence))
    for lst in list_orig
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.