Python 将多个值传递给函数
我正在尝试使用Python中的find and replace with win32com.client替换word文档中的2个字符串。基本上,我的测试文档有“First Name”和“Last Name”,从中我创建了一个新文档,用“John”和“Smith”替换这两个,但只更改了名字。我是python新手,所以我确信这显然是我做错了什么。我在这里已经有一段时间了,所以任何帮助都将不胜感激Python 将多个值传递给函数,python,ms-word,Python,Ms Word,我正在尝试使用Python中的find and replace with win32com.client替换word文档中的2个字符串。基本上,我的测试文档有“First Name”和“Last Name”,从中我创建了一个新文档,用“John”和“Smith”替换这两个,但只更改了名字。我是python新手,所以我确信这显然是我做错了什么。我在这里已经有一段时间了,所以任何帮助都将不胜感激 import win32com.client word = win32com.client.Dispa
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()
你可以
o = open("C:\TEMP\Test.docx","a") #open for append
for line in open("file"):
line = line.replace("someword","newword") # set your own names here
o.write(line + "\n")
o.close()
因此无需重新定义替换方法。因此只需使用
find.Execute(Replace=2, Forward=True)
这可能是Replace=1 Replace only first-occurrence吗?Replace的msdn状态指定要进行多少次替换:一次、全部或无。我尝试了Replace=2,结果成功了。谢谢.docx
不是文本文件。