2

Is there a way to remove a certain word from a list of sentences if that word appears after a list of words?

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?

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • 1
    Hi! Welcome to StackOverflow. *"I know how to remove a word if it appears after one particular word "* Could you please explain how you do this? Your method can probably be adapted to accommodate a list of words instead of a particular word. Please edit your question to show how you remove a word if it appears after a particular word. Then it will be easier to help you. – Stef Aug 31 '22 at 15:57

2 Answers2

1

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'
>>>
game0ver
  • 1,250
  • 9
  • 22
1

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

Sajadi
  • 154
  • 1
  • 12