如何有效地用Python替换Word文档中的句子 [英] How to effectively replace sentences in word document with python

查看:23
本文介绍了如何有效地用Python替换Word文档中的句子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我到目前为止所做的:

from docx import Document

document = Document('filename.docx')

dic = {
    'Stack':'Stack Overflow',
'October 18 2021' : 'Actual Date'}
for p in document.paragraphs:
    inline = p.runs
    for i in range(len(inline)):
        text = inline[i].text
        for key in dic.keys():
            if key in text:
                 text=text.replace(key,dic[key])
                 inline[i].text = text


document.save('new.docx')

但是当她需要替换一个单词时,这个功能似乎工作得很好,但当她需要替换句子时,它就不起作用了(这里是2021年10月18日)/

你知道为什么句子不起作用吗?

推荐答案

问题源于您正在阅读的部分句子实际上处于不同的运行中。

正如斯坎尼在this帖子中所述:

因此游程可以有效地在任意位置拆分段落文本,甚至每个字符一个游程。简而言之,Word不会尝试跟踪句子;如果你看到一串句子,那就是纯粹的巧合。

解决此问题的一个简单方法是使用paragraph.text而不是inline.text进行搜索和替换

from docx import Document

document = Document('test.docx')

dic = {
    'Stack':'Stack Overflow',
    'October 18 2021' : 'Actual Date'
}
for p in document.paragraphs:
    for key in dic.keys():
        if key in p.text:
            p.text = p.text.replace(key,dic[key])

document.save('new.docx')

这篇关于如何有效地用Python替换Word文档中的句子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆