简体   繁体   English

使用Python win32com查找并替换Word文档中的斜体

[英]Find and replace italics in Word document with Python win32com

I'm facing a big issue with the Python package win32com: My problem is that I want to find some words in a Word document, and put them in italics. 我在使用Python软件包win32com时遇到了一个大问题:我的问题是我想在Word文档中找到一些单词,并用斜体字表示。

Let's say I have the word "Hello" 10 times in my document. 假设我在文档中有10次单词“ Hello”。 I want to reach all these 10 occurrences of the word "Hello", and write them in italics. 我想看到单词“ Hello”的所有这10个出现,并用斜体写出来。

Any idea on how to do that? 关于如何做到这一点的任何想法? I've been looking for a solution for several months and I couldn't find one! 我一直在寻找解决方案已有几个月了,但找不到!

Many thanks! 非常感谢!

One solution would be to avoid using wdReplaceAll and instead simply do 一种解决方案是避免使用wdReplaceAll ,而只是做

import win32com.client
import os

word = win32com.client.Dispatch('Word.Application')
word.Documents.Open(os.path.abspath(r'.\your_document.docx'))
while word.Selection.Find.Execute('Hello'):
    word.Selection.Range.Font.Italic = True

Here, we continuously search for 'Hello' and, for each search result, use the fact that the match becomes available as the selected range. 在这里,我们连续搜索'Hello'并针对每个搜索结果使用匹配项可作为选定范围的事实。

Note that this does not wrap around the search, so if that becomes necessary in your case (which it might if you can not ensure that the search is started at the beginning of the document), you may want to use wdFindContinue (and take care to avoid potential infinite loops). 请注意,这不会围绕搜索进行环绕,因此如果您有必要这样做(如果您不能确保在文档的开头开始搜索,则可能需wdFindContinue ),您可能需要使用wdFindContinue (请注意)。以避免潜在的无限循环)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM