Home > front end >  Replace variables in a document with arguments - python
Replace variables in a document with arguments - python

Time:11-05

I want to replace variables in a .docx with arguments python. I got the script for replacement working but I don't know how to correctly print the arguments. I run my python script like:

$ python var-replace.py cat fish dog

var-replace.py looks like: `

import sys
arg1, arg2, arg3 = sys.argv[1], sys.argv[2], sys.argv[3]


from docx import Document
doc = Document('test.docx')

replacements = {
    '${replace_me_1}': "print(arg1)",
    '${replace_me_2}': "file.writelines(arg2)",
    '${replace_me_3}': "(arg3)",
    }

for paragraph in doc.paragraphs:
    for key in replacements:
        paragraph.text = paragraph.text.replace(key, replacements[key])

doc.save('test.docx')

input of test.docx: `

${replace_me_1}
${replace_me_2}
${replace_me_3}

output of test.docx after running var-replace.py: `

print(arg1)
file.writelines(arg2)
(arg3)

Expected output: `

cat
fish
dog`

How do i correctly replace the arguments to the .docx?

Additional question: How do I save the docx as sys.argv[3].docx (dog.docx)?

CodePudding user response:

Are you sure that you need to pass the values in as strings instead of calling them?

import sys
arg1, arg2, arg3 = sys.argv[1], sys.argv[2], sys.argv[3]


from docx import Document
doc = Document('test.docx')

#current - wrong approach
replacements = {
    '${replace_me_1}': "print(arg1)",
    '${replace_me_2}': "file.writelines(arg2)",
    '${replace_me_3}': "(arg3)",
    }

#possible change
replacements = {
    '${replace_me_1}': str(arg1),
    '${replace_me_2}': arg2,
    '${replace_me_3}': arg3,
    }

for paragraph in doc.paragraphs:
    for key in replacements:
        paragraph.text = paragraph.text.replace(key, replacements[key])

doc.save('test.docx')

  • Related