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

0

Good morning! I need some help ...

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

I would like to replace each term within 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? Thank you in advance!

---- 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)
    
asked by anonymous 23.10.2018 / 16:00

1 answer

0

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

The logic is as follows, first, make the for in the list, because each element of the list means a new file that you are going to generate. At each iteration, apply replacements to the entire file and save the file, before starting again with a new file and replacements:

import os
from docx import Document

caminho = r'D:\Users614879\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)
    
24.10.2018 / 05:12