Conrad Niepodam
Conrad Niepodam

Reputation: 17

Find string in text and replace it with one of the list values

My code is

my_text=" Mr. [name] [surname] live in [town]"
list1=["[name]","[surname]","[town]"]
list2=["John","Smith","London"]
for x in list1:
    number=list1.index(x)
    mytext2=my_text.replace(x,list2[number])
print(mytext2)

The original my_text is read from docx file and it is much longer. I would like to automatically find in my_text elements from list1 and replace them with right elements from list2. I try to do it with for loop but at the end it worked for the last position only. This code is not working for me.

Upvotes: 0

Views: 59

Answers (4)

Conrad Niepodam
Conrad Niepodam

Reputation: 17

My final Code which is working!

import docx2txt


def exchenage_word(first_name,surname,town):
    my_text = docx2txt.process("Umowa1.docx")
    list_to_change=["{first_name}","{surname},","{town}."]
    new_list=[first_name,surname,town]
    d = dict(zip(list_to_change, new_list))
    res = ' '.join([d.get(x, x) for x in my_text.split()])
    print(res)
first_name="John"
surname= "Smith"
town="Londyn"
exchange_word(first_name,surname,town)
# the text in Umowa1.docx is: Mr {first_name} {surname}, live in {town}.

Upvotes: 0

Conrad Niepodam
Conrad Niepodam

Reputation: 17

My orginal code is :

import docx2txt

def replace_word(first_name,surname,town):
    my_text = docx2txt.process("Umowa1.docx")
    list_of_change=["{first_name}","{surname}","{town}"]
    for x in list_of_change:
        number = list_of_change.index(x)
        z = my_text.replace(x, name)
        print(z)

# Tekst in file .docx to : Mr {first_name} {surname} live in {town}
first_name="Tom"
surname="Smith"
town="London"
replace_word(first_name,surname,town)

I would like the function to replace in file Umowa1.docx strings marked in {} to one from arguments of the function so I have in file output Mr Tom Smith live in London

Upvotes: 0

sushanth
sushanth

Reputation: 8302

If u can format the text as below,

my_text=" Mr. {name} {surname} live in {town}"

list1=["name","surname","town"]
list2=["John","Smith","London"]

my_text.format(**dict(zip(list1, list2)))

# Mr. John Smith live in London

Upvotes: 3

Austin
Austin

Reputation: 26039

This is possible with a dictionary lookup more effectively:

my_text = " Mr. [name] [surname] live in [town]"
list1 = ["[name]","[surname]","[town]"]
list2 = ["John","Smith","London"]

d = dict(zip(list1, list2))
res = ' '.join([d.get(x, x) for x in my_text.split()])

# Mr. John Smith live in London

Upvotes: 0

Related Questions