我正在尝试使用 python 和 win32 组件自动化 Word(2010) 文档(所有大多数 40-50 个文档)。具体来说,需要选择一部分行并将其全部替换为一些内容。例如,如果原始文件中有“标签:096-4296-05A”,我希望将其替换为“标签:___< em>________ ”。仅当所有文件中存在的数字相同时,使用搜索和替换才有效,但实际上并非如此。因此,在这种情况下,我希望有一种通用方法来执行此任务。
所以我在想的是,如果我可以选择包含“Label 096-4296-05A”的行并将其删除,然后再次编写一个新行,例如“标签_______”。
为此,我确实查看了@ Selection Object http://msdn.microsoft.com/en-us/library/bb221235%28v=office.12%29.aspx和 http://msdn.microsoft.com/en-us/library/bb208865%28v=office.12%29.aspx甚至尝试为 VB 编写一些等效的 python 代码。
这是我到目前为止所写的内容:
...///
########################
#
# Purpose : Replace all occurrences of `find_str` with `replace_str`
# in `word_file
#
#######################
def delete_and_add_line(word_file, find_str, replace_str):
wdFindContinue = 1
wdReplaceAll = 2
# Dispatch() attempts to do a GetObject() before creating a new one.
# DispatchEx() just creates a new one.
app = win32com.client.DispatchEx("Word.Application")
app.Visible = 0
app.DisplayAlerts = 0
app.Documents.Open(IP_Directory_Dest + "\\" + word_file) ## (word_file)
# expression.Execute(FindText, MatchCase, MatchWholeWord,
# MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward,
# Wrap, Format, ReplaceWith, Replace)
app.Selection.Find.Execute(find_str, True, True, \
False, False, False, True, \
wdFindContinue, False, replace_str, wdReplaceAll)
app.Selection.EndKey(Extend=win32com.client.constants.wdExtend)##.Select()
# determine if the text is selected or not
if (app.Selection.Type == win32com.client.constants.wdSelectionIP ):
print 'Nothing is selected'
else:
print 'Text Selected '
# to delete the selected line
app.Selection.Delete()
app.ActiveDocument.Close(SaveChanges=True)
app.Quit()
...///
当我执行此代码时,我发现 app.Selection.Find.Execute 能够成功查找并替换提供给它的文本。 即使它打印“Text Selected”,这意味着选择了行尾的文本,但它永远不会删除选定的行。
另外,我不确定这是否是完全选择一行直到其结束的正确方法(使用 Select 与此会给我属性错误“AttributeError:'int'对象没有属性'Select'”)
**### **IS THIS THE CORRECT WAY TO SELECT A LINE TILL ITS END** ???**
app.Selection.EndKey(Extend=win32com.client.constants.wdExtend)##.Select()
如果我在这里遗漏了什么,请告诉我。欢迎提出任何建议。
最佳答案
请注意,您正在执行“Selection.Find”函数获取的所有匹配项的替换,然后尝试在最后一个匹配项之后扩展选择,我不要认为这就是你想要的。我在扩展选择的方式上也遇到了错误,因为 Word 不接受此常量 (wdExtend)。
此外,最好将文档作为 finally 子句的一部分关闭,以避免将 Word 留在内存中处于未知状态。
我认为正确的解决方案是迭代文档中的所有段落,然后使用正则表达式来匹配和替换要替换的文本。正则表达式比单词查找功能强大得多。您可以使用 Range 属性的 Text 属性来访问段落的文本。像这样的东西:
import win32com.client
import re
# This is the regular expression to match the text you are after
regexp = "Label: [0-9A-Z-]+"
def replace_label(word_file):
app = win32com.client.DispatchEx("Word.Application")
app.Visible = 0
app.DisplayAlerts = 0
app.Documents.Open("C:\\" + word_file)
try:
doc = app.ActiveDocument
# Iterate over all the paragraphs
for parNo in range(1,doc.Paragraphs.Count):
paragraph = doc.Paragraphs(parNo)
# Get the text of the paragraph.
current_text = paragraph.Range.Text
# Check if there is a match in the paragraph
if re.search(regexp,current_text):
# We found a match... do the replace
paragraph.Range.Text = re.sub(regexp,"Label _______",current_text)
finally:
app.ActiveDocument.Close(SaveChanges=True)
app.Quit()
我不确定我建议的正则表达式,因此您可能需要调整它。据我所知,正则表达式的最佳指南是:
http://www.zytrax.com/tech/web/regex.htm 和 http://docs.python.org/2/library/re.html
关于python - 使用 Python/Win32 选择和删除 Word 文档中存在的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16056175/