鱼C论坛

 找回密码
 立即注册
查看: 1394|回复: 1

【求助】如何用python修改word中的文字,同时保留word中的图片

[复制链接]
发表于 2020-4-2 23:36:39 From FishC Mobile | 显示全部楼层
file.inlineshapes仅能找到内联图片,非内联图片找不到,
但通过file.paragraphs[n].runs[m].element.drawing_lst 则可返回块中的图形列表,包括内联图形和非内联图形。所以图片会存在paragraph.run内,如果直接修改paragraph.text会破坏paragraph结构,导致图片丢失。
所以解决方案就是修改下一级run中text而不动图片

  1. from docx import Document
  2. path1 = 'test_in.docx'
  3. path2 = 'test_out.docx'
  4. file = docx.Document(path1)
  5. for parg in file.paragraphs:
  6.         runt = []
  7.             for run in parg.runs:
  8.                 if run.text:
  9.                     runt.appent(run.text)
  10.                     runtext = ''
  11.             parg.add_run('test***'+''.join(runt))
  12. file.save(path2)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-9-27 02:48

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表