使用Python替换docx中的文本

时间:2016-06-13 11:55:06

标签: python csv docx

我有一个小方面的项目,我正在做的工作,以帮助我为员工创建欢迎文件的“手动”工作。

我想做的是: 1)从CSV文件中提取单元格内容(用户名,名字,密码) 2)获取单元格内容并替换DOCX文件中的[FirstName],[Username]和[Password]字符串。

这是代码:

""" Dependencies """
import csv
import numpy as np
import re
import shutil
import docx
#import fileinput

""" Open CSV and add usernames to list """
with open('UploadUsers.csv', 'rU') as csvfile:
    readCSV = np.loadtxt(csvfile, delimiter=',', skiprows=1, dtype = 'str')
    first_names = []
    usernames = []
    passwords = []

for row in readCSV:
    username = row[1]
    first_name = row[2]
    password = row[5]

    usernames.append(username)
    first_names.append(first_name)
    passwords.append(password)

for username in usernames:

    doc = "Free_Tracking_Manager_US.docx"
    doc_copy = "Free_Tracking_Manager_US.docx."+username+".docx"

    """ Make file copies """
    shutil.copy(doc, doc_copy)

    """ Make changes to first name, username and password """

    document = docx.Document(doc_copy)

    for paragraph in document.paragraphs:
        if '[FirstName]' in paragraph.text:
            print(first_name)
        if '[Username]'  in paragraph.text:
            print(username)
        if '[Password]'  in paragraph.text:
            print(password)

    """ Save document """
    document.save(doc_copy)

脚本运行时没有错误,它会复制文档,但不会替换字符串。不确定问题出在哪里......

更新:

做出了改变Abass的建议。我换了:

for paragraph in document.paragraphs:
        if '[FirstName]' in paragraph.text:
            print(first_name)
        if '[Username]'  in paragraph.text:
            print(username)
        if '[Password]'  in paragraph.text:
            print(password)

使用:

for paragraph in document.paragraphs:
        if '[FirstName]' in paragraph.text:
            print(first_name)
            paragraph.text = paragraph.text.replace('[FirstName]',first_name)
        if '[Username]'  in paragraph.text:
            print(username)
            paragraph.text = paragraph.text.replace('[Username]',username)
        if '[Password]'  in paragraph.text:
            print(password)
            paragraph.text = paragraph.text.replace('[Password]',username)

仍然不起作用......

1 个答案:

答案 0 :(得分:1)

IIUC检查完成后,您不会替换关键字字符串:

进行此更改并更换字符串。

for paragraph in document.paragraphs:
        if '[FirstName]' in paragraph.text:
            print(first_name)
            paragraph.text = paragraph.text.replace('[FirstName]',first_name)
        if '[Username]'  in paragraph.text:
            print(username)
            paragraph.text = paragraph.text.replace('[Username]',username)
        if '[Password]'  in paragraph.text:
            print(password)
            paragraph.text = paragraph.text.replace('[Password]',username)