Python docx在保持样式的同时替换段落中的字符串

2024-04-18

我需要帮助替换 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

因此,如果我实现它并想要类似的内容(包含要替换的字符串的段落会丢失其格式):

This is 第1段,这是一个文本bold.

This is 第2段,我将替换old text

目前的结果是:

This is 第1段,这是一个文本bold.

这是第 2 段,我将替换新的文字


我发布了这个问题(尽管我在这里看到了一些相同的问题),因为(据我所知)这些问题都没有解决这个问题。有一个使用 oodocx 库,我尝试过,但没有成功。所以我找到了一个解决方法。

代码非常相似,但逻辑是:当我找到包含我想要替换的字符串的段落时,使用以下命令添加另一个循环runs。 (只有当我想要替换的字符串具有相同的格式时,这才有效)。

def replace_string(filename):
    doc = Document(filename)
    for p in doc.paragraphs:
        if 'old text' in p.text:
            inline = p.runs
            # Loop added to work with runs (strings with same style)
            for i in range(len(inline)):
                if 'old text' in inline[i].text:
                    text = inline[i].text.replace('old text', 'new text')
                    inline[i].text = text
            print p.text

    doc.save('dest1.docx')
    return 1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python docx在保持样式的同时替换段落中的字符串 的相关文章

随机推荐