我试图在Python中使用win32com.client来查找和替换,以替换word文档中的两个字符串。基本上我的测试文档有'名字'&'姓',并且由此我创建一个新文档,用'John'&'Smith'替换这两个文档,但只有第一个名字被更改。我是python的新手,所以我确信这是很明显的,我做错了。我一直在这一段时间,所以任何帮助将不胜感激。将多个值传递给一个函数
import win32com.client
word = win32com.client.DispatchEx("Word.Application")
word.Visible = True
word.DisplayAlerts = 0
word.Documents.Open("C:\TEMP\Test.docx")
def replace(find_str, replace_str):
find = word.Selection.Find
find.Text = find_str
find.Replacement.Text = replace_str
find.Execute(Replace=1, Forward=True)
replace('First Name', 'John')
replace('Last Name', 'Smith')
word.ActiveDocument.SaveAs('C:\TEMP\Test2.docx')
word.Quit()
可以在此是更换= 1只替换第一次出现? – oleg
msdn指出replace指定要做多少次替换:one,all或none。我尝试了替换= 2,并做到了这一点。谢谢!! – KFP