Home > Net >  How to print out list items from a list of strings that contain any item of another list of strings
How to print out list items from a list of strings that contain any item of another list of strings

Time:04-07

I have a list of words like:

lst = [
    "white", 
    "green",
    "blue", 
    "cat", 
    "dog"
    ]

And I also have tokenized text like:

tokenized_text = ["This is a sentence.", "This is another sentence.", "This sentence contains a word from the list: cat.", "Finally, this is the last sentence."]

I'd like to print out all the list items from the tokenized_text list that contain either of the words from lst.

Based on the example above, the expected output should be: ['This sentence contains a word from the list: cat.']

I'm new to Python and already tried a few things, but the only thing that I was able to achieve is to check whether or not the text contains any of the words in the list.

EDIT: I changed the list name to lst from list.

CodePudding user response:

In case you don't want list comprehension

for word in lst:
  for token in tokenized_text:
    if word in token:
      print(token)
  • Related