how to replace words of a sentence with the given words

Question:

I want to replace some words in the sentence with the given words and their replacements.
In the first line of code, you get the number of words that the user gives, then the words and their replacements and a last the sentence that should change
If there is any word in the sentence given, it should change. Otherwise, it will print the word itself.
for example:
user entry:

5
hello salam
goodbye khodafez
say goftan
we ma
you shoma

we say goodbye to you tonight


output:
ma goftan khodafez to shoma tonight

I wrote this code and the problem is to find the word and change

n=int(input())
words=[]
trans=[]
dict1={}
for i in range(0,n):
    word_trans=input()
    word_trans = word_trans.split()
    words.append(word_trans[0])
    trans.append(word_trans[1])
for i in range(0,n):
    dict2={words[i]:trans[i]}
    dict1.update(dict2)
sentence=input()
sentence1=sentence.split()
for i in sentence1:
    if i==dict1(keys):
        print(dict1(key))
    else:
        print(i)
Asked By: liehos98

||

Answers:

Here is one solution with a few minor changes to fix your use of the translation dictionary and accumulating the translated results before finally printing the resulting sentence on one line.

n = int(input("Count of replacement words:"))

words = []
trans = []
dict1 = {}

for i in range(n):
    word_trans = input("Enter old new:")
    word_trans = word_trans.split()
    words.append(word_trans[0])
    trans.append(word_trans[1])

for i in range(n):
    dict1[words[i]] = trans[i]

output = []
sentence = input("Enter sentence:")

for word in sentence.split():
    if word in dict1:
        output.append(dict1[word])
    else:
        output.append(word)

print(" ".join(output))

Here is a more compact version of that code with less state:

n = int(input("Count of replacement words: "))

word_map = {}

for _ in range(n):
    words = input("Enter old new: ").split()
    word_map[words[0]] = words[1]

sentence = input("Enter sentence: ")    
output = [word_map.get(word, word) for word in sentence.split()]

print("Result:", " ".join(output))
Answered By: jarmod
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.