I've tried a few different methods. And I don't understand why none of them are working. But I guess we can just focus on the last one. A simple while for loop. If you have time, and you can tell me why the other methods don't work either, that would be much appreciated.
Write a program that replaces words in a sentence. The input begins with word replacement pairs (original and replacement). The next line of input is the sentence where any word on the original list is replaced.
Ex: If the input is:
automobile car manufacturer maker children kids
The automobile manufacturer recommends car seats for children if the automobile doesn't already have one.
the output is:
The car maker recommends car seats for kids if the car doesn't already have one.
You can assume the original words are unique.
wordPairs = input()
sentence = input()
tokens = wordPairs.split()
newDict = {tokens[i]:tokens[i+1] for i in range(len(tokens)) if i % 2 != 1}
#for index,value in enumerate(newDict.keys()):
#for i in sentence.split():
#if i == value:
#sentence.replace(i,newDict[value])
#print(sentence)
#for i in sentence.split():
#for key in newDict.keys():
#if i == newDict[key]:
#sentence.replace(i,newDict[key])
#print(sentence)
x = 0
while x <= len(tokens)-1:
for i in tokens:
sentence.replace(tokens[x],tokens[x+1])
x+=2
print(sentence)
Program output displayed here
The automobile manufacturer recommends car seats for children if the automobile doesn't already have one.