Home > Back-end >  Replacement words
Replacement words

Time:10-11

I am trying 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. Here is the code I have so far:

pair_prompt = input()
sentence_prompt = input()

pair = pair_prompt.split('  ')
my_dict = dict(s.split() for s in pair)
sentence = sentence_prompt.split()

for key, value in my_dict.items():
    if key in sentence:
    index = sentence.index(key)
    sentence[index] = value

print(' '.join(sentence))

Input for pair_prompt is: automobile car manufacturer maker children kids

Input for sentence_prompt is: The automobile manufacturer recommends car seats for children if the automobile doesn't already have one.

Output is supposed to be: The car maker recommends car seats for kids if the car doesn't already have one.

For some reason the output is: The car maker recommends car seats for kids if the automobile doesn't already have one.

What can I do to fix this?

CodePudding user response:

Your issue is that your program is only replacing at most one occurrence of the substring in the main string.

For instance, the first automobile becomes car, but the second one doesn't.

If you want to do this in a clean way, you can leverage the replace() method.

for key, value in my_dict.items():
    sentence_prompt = sentence_prompt.replace(key, value)
print(sentence_prompt)

If you really want to do it manually by manipulating sentence, you can use a nested loop

for key, value in my_dict.items():
    # Use a while instead of the if so that you get all
    # occurrences replaced, not just the first one
    while key in sentence:
       index = sentence.index(key)
       sentence[index] = value

CodePudding user response:

You can do this without looping using regex as re.sub can use a function as it's replacement:

pair_prompt = input("pair: ")
sentence = input("sentence: ")

pairs = pair_prompt.split()
translation = dict(zip(pairs[::2], pairs[1::2]))

def get_translation(match): 
    s = match[0]
    return translation.get(s, s)

print(re.sub('|'.join(translation), get_translation, sentence, ))

>>> pair: automobile car manufacturer maker children kids
>>> sentence: The automobile manufacturer recommends car seats for children if the automobile doesn't already have one.
The car maker recommends car seats for kids if the car doesn't already have one.
  • Related