Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to replace words of a sentence bye given words

I want to replace some words of a sentence bye given words and their replacements
the first line of code you get the number of words that user give, then the words and their replacements and a last the sentence that should change
if there is any word of sentence in words given, it should change but if not in the words given 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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading