2013-05-15 7 views
5

Sto cercando di aggiungere più valori di stringa a un documento di Word utilizzando Trova e sostituisci con la libreria Python win32com.client.utilizzando win32com.client in python come trovare e sostituire più testo

Posso trovare e sostituire un valore, ma non so come farlo per più valori.

Questo è quello che ho finora:

import win32com.client 
word = win32com.client.DispatchEx("Word.Application") 
word.Visible = True 
word.DisplayAlerts = 0 
word.Documents.Open("C:\TEMP\Testing\Me.docx") 
word.Selection.Find 
find.Text = "First Name" 
find.Replacement.Text = "John" 
find.Execute(Replace=1, Forward=True) 

# the following part doesn't run 
find.Text = "Last Name"    
find.Replacement.Text = "Smith" 
find.Execute(Replace=1, Forward=True) 

word.ActiveDocument.SaveAs('C:\TEMP\Testing\Me2.docx') 
word.Quit() # releases Word object from memory 

Qualche suggerimento?

risposta

5

Prova questo:

import win32com.client 
from os import getcwd, listdir 

docs = [i for i in listdir('.') if i[-3:]=='doc' or i[-4:]=='docx'] #All Word file 

FromTo = {"First Name":"John", 
      "Last Name":"Smith"} #You can insert as many as you want 


word = win32com.client.DispatchEx("Word.Application") 
word.Visible = True #Keep comment after tests 
word.DisplayAlerts = False 

for doc in docs: 
    word.Documents.Open('{}\\{}'.format(getcwd(), doc)) 
    for From in FromTo.keys(): 
     word.Selection.Find.Text = From 
     word.Selection.Find.Replacement.Text = FromTo[From] 
     word.Selection.Find.Execute(Replace=2, Forward=True) #You made the mistake here=> Replace must be 2 
    name = doc.rsplit('.',1)[0] 
    ext = doc.rsplit('.',1)[1] 
    word.ActiveDocument.SaveAs('{}\\{}_2.{}'.format(getcwd(), name, ext)) 

word.Quit() # releases Word object from memory