我需要帮助替换word文档中的字符串,同时保持整个文档的格式.
我正在使用python-docx,在阅读文档之后,它适用于整个段落,所以我放松了格式,如粗体或斜体字.包括要替换的文本是粗体,我想保持这种方式.我正在使用此代码:
from docx import Document
def replace_string2(filename):
    doc = Document(filename)
    for p in doc.paragraphs:
        if 'Text to find and replace' in p.text:
            print 'SEARCH FOUND!!'
            text = p.text.replace('Text to find and replace', 'new text')
            style = p.style
            p.text = text
            p.style = style
    # doc.save(filename)
    doc.save('test.docx')
    return 1
Run Code Online (Sandbox Code Playgroud)
因此,如果我实现它并想要类似的东西(包含要替换的字符串的段落丢失其格式):
这是第1段,这是一个粗体文本.
这是第2段,我将替换旧文本
目前的结果是:
这是第1段,这是一个粗体文本.
这是第2段,我将替换新的文本