700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python去除文档水印 删除页眉页脚

python去除文档水印 删除页眉页脚

时间:2024-05-06 20:25:20

相关推荐

python去除文档水印 删除页眉页脚

处理前效果

处理后

读取doc文档报错:raise ValueError(tmpl % (docx, document_part.content_type))

from docx import Documentpath = r"D:\\demo\\北京高考文数试题及答案2.doc"doc = Document(path)

ValueError: file ‘D:\北京高考文数试题及答案2.doc’ is not a Word file, content type is ‘application/vnd.openxmlformats-officedocument.themeManager+xml’**

首先确定了文档是存在且有内容,路径也没问题,

wps可以正常打开,但是doc是旧版本的格式读取

可用win32com.client包打开

import win32com.client as wcword = wc.Dispatch("Word.Application")doc = word.Documents.Open(file_path, Encoding='utf-8')

原本是想着先转换格式为docx再读取,太麻烦

直接上代码了

代码方式1

"""去除水印"""import comtypes.clientword = comtypes.client.CreateObject('Word.Application')doc = word.Documents.Open(path)clean_text = []# 删除页眉,页脚for section in doc.Sections:for header in section.Headers:if header.Range.Text and len(header.Range.Text) > 2:clean_text += str(header.Range.Text).strip().split()header.Range.Delete()for footer in section.Footers:if footer.Range.Text and len(footer.Range.Text) > 2:clean_text += str(footer.Range.Text).strip().split()footer.Range.Delete()## 替换文档内容if clean_text:for target_text in set(clean_text):## 不想替换页码if str(target_text).isdigit() or len(target_text) < 5:continuefor content_range in doc.StoryRanges:content_range.Find.Execute(target_text, False, False, False, False, False, True, 1, False, '',2)# doc.SaveAs()doc.SaveAs('{}x'.format(path), 16) # 16 表示保存为docx格式doc.Close()word.Quit()

代码方式2

from docx import Documentdef clean_words(self, file_path, target_text):""" 清洗文档:替换页眉页脚内容 """doc = Document(file_path)# 获取所有节的页眉和页脚for section in doc.sections:# 获取页眉header = section.headerif header is not None:# 获取页眉的段落for p in header.paragraphs:# 替换页眉中的目标文字为空p.text = p.text.replace(p.text, "")# 获取页脚footer = section.footerif footer is not None:# 获取页脚的段落for p in footer.paragraphs:logger.info(p.text)# 替换页脚中的目标文字为空p.text = p.text.replace(p.text, "")# 替换文档内容的方式2:使用Document.paragraphs属性和Paragraph.text属性for i, p in enumerate(doc.paragraphs):for w in target_text:if w in p.text:p.text = p.text.replace(w, "")doc.save(file_path)doc.close()```

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。