python - 如何从 docx 文件中提取文本和图像并将其写入新的 docx 文件,只需进行少量更改
问题描述
我正在尝试使用 doc.paragrapgh 上的循环替换文本。我成功替换了文本,但是图像被删除了。我想保留图像,只想替换文本。在此先感谢我正在使用下面的代码
from docx import Document
from docx.table import _Cell
doc = Document("abc.docx")
for p in doc.paragraphs:
if 'CORREDOR' in p.text:
text = p.text.replace(p.text, "VIGENCIA").strip()
style = p.style
p.text = text
p.style = style
elif 'DECLARACIÓN DE NO SINIESTRALIDAD' in p.text:
text= p.text.replace(p.text, "DECLARACIÓN DE SINIESTRALIDAD")
style = p.style
p.text = text
p.style = style
doc.save('result4.docx')
解决方案
保存到相同的名称(即:)doc.save('abc.docx')
可能会解决您的问题。
或者您可以shutil.copy('abc.docx', 'result4.docx')
在使用docx
.