Python - scroll through a list - replace word within word (.docx)

Asked

Viewed 492 times

0

Good morning! I need some help...

I have a word file, named after 'docx test.'.

I would like to replace each term inside it with strings that are in a list. See example.

The problem that is occurring is that the change is not looping.

Can you help me? Thanks in advance!

inserir a descrição da imagem aqui

----x----

from docx import Document

caminho = 'D:\\Users\\89614879\\Desktop\\Nova pasta\\'
arquivo = 'teste.docx'
docword = caminho + arquivo

doc = Document(docword)

lista = [['111','adm','Pedro Paulo'],['222','cont','Luiz Carlos'],['333','econ','Jorge Fernando'],['444','jorn','Claudia Leite']]
qtd_linhas = len(lista)
qtd_colunas = len(lista[0])

nome_arq = ['Pedro Paulo', 'Luiz Carlos', 'Jorge Fernando','Claudia Leite']

for i, paragrafo in enumerate(doc.paragraphs):
    palavra = '<' + str(i) + '>'
    if palavra in paragrafo.text:
        for x in range(qtd_linhas):
            for y in range(qtd_colunas):
                paragrafo.text = paragrafo.text.replace(palavra, str(lista[x][y]))
                new_docword = caminho + nome_arq[y] + '.docx'
                doc.save(new_docword)

1 answer

0


Your code is almost fine, just a few things that are reversed.

The logic is this, first, do the for in the list, because each element in the list means a new file that you will generate. In each iteration, apply the overwrites to the entire file and save the file, before starting again with new file and new overwrites:

import os
from docx import Document

caminho = r'D:\Users\89614879\Desktop\Nova pasta'
arquivo = 'teste.docx'
docword = os.path.join(caminho, arquivo)

lista = [['111','adm','Pedro Paulo'],['222','cont','Luiz Carlos'],['333','econ','Jorge Fernando'],['444','jorn','Claudia Leite']]
nome_arq = ['Pedro Paulo', 'Luiz Carlos', 'Jorge Fernando','Claudia Leite']

for novo_nome, substituicoes in zip(nome_arq, lista):
    doc = Document(docword)
    for paragrafo in doc.paragraphs:
        for i, substituicao in enumerate(substituicoes):
            palavra = '<' + str(i) + '>'
            if palavra in paragrafo.text:
                paragrafo.text = paragrafo.text.replace(palavra, substituicao)
    new_docword = os.path.join(caminho, novo_nome + '.docx')
    doc.save(new_docword)
  • nosklo, thank you for your attention. Thank you for the guidance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.