您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

我发布了这个问题(即使我在这里看到了几个相同的问题),因为(据我所知)这些问题都没有解决这个问题。我曾经尝试过使用oodocx库,但是没有用。所以我找到了一种解决方法。@H_419_1@

代码非常相似,但是逻辑是:当我找到包含要替换的字符串的段落时,请使用 添加一个循环。(这仅在我要替换的字符串具有相同格式的情况下才有效)。@H_419_1@

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
python 2022/1/1 18:33:25 有488人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶