I'm working on replacing words using two lists
a = ["Strawberry Cookie", "Banana Cookie", "Tomato Cookies", "Pineapple Cookie", "Apple Cookie"]
b = ["Pineapple Cookie", "Cookie Banana", "Cookie Tomato", "Strawberry Cookie", "Cookie Apple"]
Retrieves the string in variable text1 into a list (a) and replaces it with a list (b). The sequence of tasks is in the same order as the list.
text1 = """
Meaningless texts are listed aaaa
aaaaaaaaa Strawberry Cookie aaaaaaa
ccccc Meaningless texts are listed aaaaa
aaaaaaaaa Banana Cookie aaaaaa
bbbb Meaningless texts are listed aaaa
aaaaaaaa Tomato Cookies aaaaaaaa
aaaa Meaningless texts are listed aaaa
aaaaaaaa Pineapple Cookie aaaaaaa
aaaaaa Apple Cookie aaaaaaa
gggsdgg Meaningless texts are listed affff
dsddsssf
"""
I tried the code below.
for x, y in zip(a, b):
text1 = re.sub(x, y, text1, re.IGNORECASE)
print text1
>>>Meaningless texts are listed aaaa
aaaaaaaaa Strawberry Cookie aaaaaaa
ccccc Meaningless texts are listed aaaaa
aaaaaaaaa Cookie Banana aaaaaa
bbbb Meaningless texts are listed aaaa
aaaaaaaa Cookie Tomato aaaaaaaa
aaaa Meaningless texts are listed aaaa
aaaaaaaa Strawberry Cookie aaaaaaa
aaaaaa Cookie Apple aaaaaaa
gggsdgg Meaningless texts are listed affff
dsddsssf
Due to the duplicate values of Strawberry Cookie and Pineapple Cookie in the list (a) and (b), the replacement operation is made twice and it returns to the original value.
What I want is to set the value to not change once it is substituted.
new_text = []
check_list = []
num = 0
division = text.split('\n')
for line in division:
for i in range(len(b)):
if a[i] in line:
if a[i] not in check_list:
check_list.append(b[i])
rrr = re.sub(a[i], b[i], line, re.IGNORECASE)
new_text.append(rrr)
break
else:
check_list.append(b[i])
new_text.append(line)
else:
check_list.append(b[i])
new_text.append(line)
break
I've tried several times, but failed. Help