在python中使用win32com.client如何查找和替换多个文本 [英] using win32com.client in python how to find and replace multiple text
本文介绍了在python中使用win32com.client如何查找和替换多个文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用查找将多个字符串值添加到Word文档中,并替换为 win32com.client Python库.
I'm trying to add multiple string values to a Word document using find and replace with the win32com.client Python library.
我可以找到并替换一个值,但是我不知道如何对多个值执行此操作.
I can find and replace one value, but I don't know how to do this for multiple values.
这是我到目前为止所拥有的:
This is what I have so far:
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
有什么建议吗?
推荐答案
尝试一下:
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
这篇关于在python中使用win32com.client如何查找和替换多个文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文