2016-06-13 107 views
0

我有一個小項目,我在工作中幫助完成爲員工創建歡迎文檔的「手動」工作。使用Python替換docx中的文本

我試圖做的是: 1)從一個CSV文件(用戶名,名字,密碼) 2)取單元格內容和替換字符串[名字],[用戶名]和提取細胞內容物[密碼]在DOCX文件中。

這是代碼:

""" 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

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) 
+0

謝謝,仍然沒有工作......它使文件副本,但不會更改docx中的內容。 –

+0

請更新您的問題,並更改您所做的更改。 – Abbas

+0

完成!讓我知道還有什麼需要做的工作! –