我如何搜索和用 python 替换 ms word 文档中所有出现的字符串?
我现在很困惑。基于 我可以使用 Win32 COM 来替换 Word 文档中的文本? 我能够编写一个简单的模板系统,该系统从模板 Word 文档(Python 中)生成 Word 文档。
我的问题是“文本字段”中的文本不是这样找到的。即使在 Word 本身中,也没有搜索所有内容的选项 - 您实际上必须在“主文档”和“文本字段”之间进行选择。作为 Windows 世界的新手,我尝试浏览 VBA 文档,但没有找到任何帮助(可能是因为“文本字段”是一个非常常见的术语)。
word.Documents.Open(f)
wdFindContinue = 1
wdReplaceAll = 2
find_str = '\{\{(*)\}\}'
find = word.Selection.Find
find.Execute(find_str, False, False, True, False, False, \
True, wdFindContinue, False, False, False)
while find.Found:
t = word.Selection.Text.__str__()
r = process_placeholder(t, answer_data, question_data)
if type(r) == dict:
errors.append(r)
else:
find.Execute(t, False, True, False, False, False, \
True, False, False, r, wdReplaceAll)
这是我的代码的相关部分。我现在已经能够自己解决所有问题(提示:如果你想替换超过 256 个字符的字符串,你必须通过剪贴板等来完成......)
I am pretty stumped at the moment. Based on Can I use Win32 COM to replace text inside a word document? I was able to code a simple template system that generates word docs out of a template word doc (in Python).
My problem is that text in "Text Fields" is not find that way. Even in Word itself there is no option to search everything - you actually have to choose between "Main Document" and "Text Fields". Being new to the Windows world I tried to browse the VBA docs for it but found no help (probably due to "text field" being a very common term).
word.Documents.Open(f)
wdFindContinue = 1
wdReplaceAll = 2
find_str = '\{\{(*)\}\}'
find = word.Selection.Find
find.Execute(find_str, False, False, True, False, False, \
True, wdFindContinue, False, False, False)
while find.Found:
t = word.Selection.Text.__str__()
r = process_placeholder(t, answer_data, question_data)
if type(r) == dict:
errors.append(r)
else:
find.Execute(t, False, True, False, False, False, \
True, False, False, r, wdReplaceAll)
This is the relevant portion of my code. I was able to get around all problems by myself by now (hint: if you want to replace strings with more than 256 chars, you have to do it via clipboard, etc ...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许您可以使用 OpenOffice API 使用 UNO 组件技术。使用 Python-UNO 桥,您可以连接到以无头方式运行的 OpenOffice 实例模式。请参阅教程开始使用。
对于您的场景来说,这可能有点过分了,但它是一个非常强大且灵活的解决方案。
Maybe you can use the OpenOffice API using the UNO component technology. With the Python-UNO bridge you can connect to an OpenOffice instance running in headless mode. Look at the tutorial to get started.
This is maybe an overkill for your scenario but it's a very powerful and flexible solution.