使用python删除word文档中的指定段落,顺便实现一下文档中的图片导出
2022/4/28 17:12:40
本文主要是介绍使用python删除word文档中的指定段落,顺便实现一下文档中的图片导出,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#! /etc/env/bin python3 #! *_* coding=utf8 *_* from pathlib import Path from docx import Document import os # 从word中导出图片 def extract_img_word(filename='',doc_path=''): ''' docx文档其实也是一个zip压缩包,所以我们可以通过zip包解压它 也可以直接改文件后缀 ''' from zipfile import ZipFile with ZipFile(filename) as zip_file: for names in zip_file.namelist(): if names.startswith("word/media/image"): zip_file.extract(names, doc_path) ''' pip install python-docx https://python-docx.readthedocs.io/en/latest/ ''' #创建文档 def createWord(): document = Document() document.add_heading('Document Title', 0) document.add_paragraph('A plain paragraph having some') document.add_heading('Heading, level 1', level=1) document.add_heading('Heading, level 1', level=2) document.add_paragraph('以下段落需要删除') document.add_paragraph('A plain paragraph') document.add_paragraph('A plain paragraph 新段落') document.add_heading('Heading, level 2', level=2) document.save('H:/temp/test.docx') createWord() #删除指定段落 def delete_paragraph(paragraph): p = paragraph._element p.getparent().remove(p) # p._p = p._element = None paragraph._p = paragraph._element = None def delWordContent(docx_file='',dest_file=''): #读取文本 doc = Document(docx_file) paragraphs = doc.paragraphs i = 0 flag = False for p in paragraphs: i+=1 #print(str(i)) #print(p.text) if p.text.find('需要删除') > -1: #print('找到了') flag = True if flag is True: #print('deleting') delete_paragraph(p) if flag is True: #保存为新文件 doc.save(dest_file) delWordContent(docx_file='H:/temp/test.docx',dest_file='H:/temp/test-new.docx') def testDel(): dest_dir = 'words' for filename in Path('H:/').glob('*.docx'): print(str(filename)) dest_file = str(filename.parent / f'{dest_dir}'/filename.name) delWordContent(docx_file = str(filename), dest_file = dest_file) os.remove(str(filename))
这篇关于使用python删除word文档中的指定段落,顺便实现一下文档中的图片导出的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-01Python编程基础知识
- 2024-11-01Python编程基础
- 2024-10-31Python基础入门:理解变量与数据类型
- 2024-10-30Python股票自动化交易资料详解与实战指南
- 2024-10-30Python入行:新手必读的Python编程入门指南
- 2024-10-30Python入行:初学者必备的编程指南
- 2024-10-30Python编程入门指南
- 2024-10-30Python量化交易学习:新手入门指南
- 2024-10-30Python股票自动化交易实战入门教程
- 2024-10-29Python股票自动化交易教程:新手入门指南