python docx 模块替换 word内容

from docx import Document

doc = Document(r’D:\python\Python37\testWord\卢祥和.docx’)
‘’’
paragraph = document.add_paragraph(‘这是个段落11。’) #将一段新文本添加到文档末尾
prior_paragraph = paragraph.insert_paragraph_before(‘这是前面的段落11。’)
paragraph1 = document.add_paragraph(‘这是个段落22。’)
prior_paragraph = paragraph1.insert_paragraph_before(‘这是前面的段落22。’)

document.save(r’D:\python\Python37\testWord\new-file-name.docx’)’’’
print(len(doc.paragraphs))#paragraphs是document文档对象的段落列表
print(doc.paragraphs[0].text)#输出paragraphs第一段的文本!Paragraphs对象具有text属性,包含段落中的纯文本字符串(没有样式信息)。
print(len(doc.paragraphs[0].runs))#’’‘Word文档中的文本不仅仅是字符串。它包含与之相关的字体、大小、颜色和其他样式信息。在Word中
#,样式是这些属性的集合。一个Run对象是相同样式文本的延续。当文本样式发生改变时,就需要一个新的Run对象。’’’’

def replace_text(old_text, new_text):
for p in doc.paragraphs:
if old_text in p.text:
inline = p.runs
for i in inline:
if old_text in i.text:
text = i.text.replace(old_text, new_text)
i.text = text

replace_text(“卢祥和”,“123”)
doc.save(r’D:\python\Python37\testWord\new-file-name.docx’)

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值