用用户输入的变量替换.docx文件中的变量

时间:2018-08-03 05:39:22

标签: python python-3.x

我有一个正在进行的项目。我有一个已创建的.docx模板。 在其中,我在整个文档中有多个变量,需要用用户输入的信息替换(某些变量在文档中多次替换)。 我有从以前使用过的.txt文件中修改过的这段代码。我无法获取.docx文件,无法使用用户估算的信息编辑var,并创建一个可以共享/打印的新文件。任何帮助,将不胜感激。

我试图尝试使用python-docx,但是,我还没有完全理解这个概念并使它起作用。

示例代码如下:

from __future__ import with_statement
import fileinput

#def terms and ask user for imput
def loaDocOne():
    words = ["[clientName]","[addressLine1]","[addressLine2]","[todaysDate]","[fileNum]","[originalClient]","[refNum]","[currentBal]","]
    clientName = input('Enter Clients name: ')
    addressLine1 = input('Enter Clients Address Line 1: ')
    addressLine2 = input('Enter Clients Address Line 2: ')
    todaysDate = input('Enter Todays Date: ')
    fileNum = input('Enter File Number: ')
    originalClient = input('Enter Original Client: ')
    refNum = input('Enter Original Refrence Number: ')


    #open file
def replaceFunc():
    with open ('template.docx') as f:
            for line in f:
                line = line.replace("[clientName]",clientName)
                line = line.replace("[addressLine1]",addressLine1 )
                line = line.replace("[addressLine2]",addressLine2 )
                line = line.replace("[todaysDate]",todaysDate)
                line = line.replace("[fileNum]",fileNum )
                line = line.replace("[originalClient]", originalClient)
                line = line.replace("[refNum]",refNum )



 #Find out if everything looks good to continue
def goOn():
    doYouWantToContinue = input('Does Everything Look Correct? yes/no: ')
    if doYouWantToContinue == 'yes':
        replaceFunc()
    else:
        loaDocOne()




loaDocOne()
goOn()
replaceFunc()

还有,是否可以采用输出的文件并使用用户提供的文件号将其设置为“ document_name_'fileNum”?

1 个答案:

答案 0 :(得分:1)

使用python-docx模块是最简单的方法。使用此模块打开的文档的结构为documented here,我认为将头绕起来很容易。

此代码打开一个文档,然后使用str.replace函数自动替换所有出现的某些字符串,用替换的文本将其替换为每个文本。

from docx import Document

doc = Document('document.docx')

replacements = {
    '%replace_me_1%': 'New text 1',
    '%replace_me_2%': 'New text 2'
    }

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

doc.save('document.docx')

使用新名称保存文件应该很容易:

file_suffix = input()
doc.save('document_' + file_suffix + '.docx')