Home > Blockchain >  Check if a word exists at a particular position of a list
Check if a word exists at a particular position of a list

Time:09-05

Suppose I have a list of lists.

List1=[["Red is my favorite color."],["Blue is her favorite."], ["She is really nice."]]

Now I want to check if the word 'is' exists after a certain set of words.

I made a word lise word_list=['Red', 'Blue']

Is there a way to check that using if statement?

If I write if 'is' in sentences: It will return all three sentences in List1, I want it to return first two sentences.

Is there a way to check if the word 'is' is positioned exactly after the words in word_list? Thank you in advance.

CodePudding user response:

NB. I assumed a match in the start of the string. For a match anywhere use re.search instead of re.match.

You can use a regex:

import re

regex = re.compile(fr'\b({"|".join(map(re.escape, word_list))})\s is\b')
# regex: \b(Red|Blue)\s is\b

out = [[bool(regex.match(x)) for x in l]
       for l in List1]

Output: [[True], [True], [False]]

Used input:

List1 = [['Red is my favorite color.'],
         ['Blue is her favorite.'],
         ['She is really nice.']]

word_list = ['Red', 'Blue']

If you want the sentences:

out = [[x for x in l if regex.match(x)]
       for l in List1]

Output:

[['Red is my favorite color.'],
 ['Blue is her favorite.'],
 []]

Or as flat list:

out = [x for l in List1 for x in l if regex.match(x)]

Output:

['Red is my favorite color.',
 'Blue is her favorite.']

CodePudding user response:

You could try this:

List1 = [['Red is my favorite color.'],['Blue is her favorite.'], ['She is really nice.']]
listResult = []
word_list = ['Red', 'Blue']
for phrase in List1:
    for word in word_list:
        if f'{word} is' in phrase[0]:
            listResult.append(phrase[0])

CodePudding user response:

Already answered.

See re module documentation: https://docs.python.org/3/library/re.html

Stack overflow previously answered question: Check if string matches pattern

  • Related