Home > Mobile >  Remove a certain word from a list of sentences
Remove a certain word from a list of sentences

Time:09-01

Is there a way to remove a certain word from a list of sentences if that word appears after a list of words? A bit confusing. For example I want to remove the word "and" if "and" appears after a list of words ([ "red", "blue", "green"]). I know how to remove a word if it appears after one particular word but is there a way to do the same for a list of words? A regular expression? Thanks in advance.

CodePudding user response:

A way you can do this is by using regex:

>>> l = [ "red", "blue", "green", "and"]
>>> k = [ "red", "blue", "green", "brown", "and"]
>>>
>>> re.sub(r"redbluegreen(?=and)", "", ''.join(l))
'and'
>>> re.sub(r"redbluegreen(?=and)", "", ''.join(k))
'redbluegreenbrownand'
>>>

CodePudding user response:

I solved it with this method:

l = [ "red", "blue", "green", "and"]
k = [ "red", "blue", "green", "brown", "and"]

str1 = ' '.join(str(e) for e in l)
str2 = ' '.join(str(e) for e in k)

s = list(dict.fromkeys(l k))
s.remove('and')
print(s)

Result

['red', 'blue', 'green', 'brown']

I hope it is useful

  • Related