• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Python批量替换多个word文档的指定

武飞扬头像
Small_小菜鸟
帮助1

需求

最近有一个项目方案,涉及到2000多个文档。之前公司有相关案例,但是需要将2000多个文档中的特殊名称改成现有项目,单独操作需要打开每个文档区搜索替换,费事费力。通过python中对文档的操作进行批量替换。

方案思路

1.获取所有需要替换的word文件路径

def getdocreplace(path):   
    files=[]
    for dirpath, dirnames, filenames in os.walk(path):
        for filepath in filenames:
            if filepath.endswith(".doc") or filepath.endswith("docx"):
                files.append(os.path.join(dirpath, filepath))
    return files

2.批量打开word,遍历循环word中的每一行进行查找替换,核心代码如下

def info_update(docfile,old_info,new_info):
    for para in docfile.paragraphs:
        for run in para.runs:
            run.text = run.text.replace(old_info,new_info)
    for table in docfile.tables:
        for row in table.rows:
            for cell in row.cells:
                cell.text = cell.text.replace(old_info,new_info)

心得体会

python真是一个好用的编程语言,语法简单,代码简洁易于编写。同时python社区有各种各样的python库,具有强大的功能。如这次简单的一个案例,如果人工去改上千的文档,需要大量时间。通过python简单的几十行代码,很短的时间就能完成大量工作。而且学习容易,入门简单。

之前还有很多解决日常工作中的案例以及以后还会用的更多的案例我会分享到51。下面是本次案例的全部代码。本段功能需要引用os和docx两个库。我使用的python版本为3.7。

import os
import docx
#获取要替换的所有文件路径,path为最外层文件夹。
def getdocreplace(path):
    files = []
	for dirpath,dirnames,filenames in os.walk(path):
        for filepath in filenames:
            if filepath.endswith(".doc") or filepath.endswith("docx"):
                files.append(os.path.join(dirpath,filepath)
   	return files

#遍历替换一个word文件中的字段,old_info为要替换的旧字段,new_info为新字段
def info_update(docfile,old_info,new_info):
    for para in docfile.paragraphs:
        for run in para.runs:
            run.text = run.text.replace(old_info,new_info)
    for table in docfile.tables:
        for row in table.rows:
            for cell in row.cells:
                cell.text = cell.text.replace(old_info,new_info)
#执行操作
if __name__ =="__main__":
   path = "d:\docfile"
   files = getdocreplace(path)
   for file in files:
       doc = docx.Document(file)
       info_update(doc,"old_project","new_project")
       doc.save(file)
       print("{}替换完成".format(file))

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhibgjcg
系列文章
更多 icon
同类精品
更多 icon
继续加载