-1

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.
skysthelimit91
  • 103
  • 1
  • 3
  • 11

1 Answers1

2

You already have a dictionary. Don't go trolling through the split words. And remember that replace doesn't replace in place -- you can't modify a Python string. It RETURNS the changed string.

for k,v in newDict.items():
    sentence = sentence.replace( k, v )

I might also suggest you replace this:

newDict = {tokens[i]:tokens[i+1] for i in range(len(tokens)) if i % 2 != 1}

with this, which is simpler:

newDIct = {tokens[i]:tokens[i+1] for i in range(0,len(tokens),2)}
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Wow....that first method certainly would have been simpler. I've been working on this over an hour lol. How long do I have to do this before I can solve problems this quickly? Also, thanks for reminding me replace just returns the changed string. After I set sentence = the replace statement, the for loop works as well. Thank you. This is so tough to learn and remember by myself. – skysthelimit91 Apr 25 '22 at 02:01