I have a list of words list_words =["cat","dog","animals"]
And i have a text = "I have a lot of animals a cat and a dog"
I want a regex code that is able to add a comma at the end of every word before any word in the list given.
I want my text to be like that: text = "I have a lot of, animals a, cat and a, dog"
My code so far:
import re
list_words = ["cat", "dog", "animals","adam"]
text = "I have a lot of animals, cat and a dog"
for word in list_words:
if word in text:
word = re.search(r" (\s*{})".format(word), text).group(1)
text = text.replace(f" {word}", f", {word}")
print(text)
But i have 2 issues here:
1: if i have a text like this : text= I have a lot of animals cat and a dogy
it turns it into : text= I have a lot of, animals, cat and a, dogy
which is not the result wanted, i wanted to replace only the word itself not with
addition like dogy
2: if i have a text like this: text= I have a lot of animals, cat and a dogy
it still add another comma which is not what i want