5分钟根治Word文档强迫症!Word文档批量改名术

朋友们,今天我分享一个让Word文档自动‘整容’的代码! 你是否有过这样的崩溃时刻?

老板甩来100个Word文档,让你把里面的“甲方爸爸”全部改成“尊贵的上帝客户”…

表格里的“预算不足”要换成“战略性成本优化”,但手动改到眼瞎?

改完还怕漏了某个角落没替换?结果熬夜检查到凌晨3点,发际线又后退1cm…

别慌!今天这个Python脚本,堪称「文档替换界的扫地僧」!
保姆级教程,连你家猫都能学会!
代码:

#暴力替换大法
from docx import Document
import os
import logging

# 设置日志
logging.basicConfig(filename='replace_keywords.log', level=logging.INFO, format='%(asctime)s - %(message)s')

def replace_keywords_in_docx(docx_path, replacements):
    doc = Document(docx_path)  # 打开文档
    # 替换段落中的关键字
    for para in doc.paragraphs:
        for old, new in replacements.items():
            if old in para.text:
                para.text = para.text.replace(old, new)
                logging.info(f"Replaced '{old}' with '{new}' in段落 {docx_path}")
    # 替换表格中的关键字
    for table in doc.tables:  # 遍历文档中的表格
        for row in table.rows:  # 遍历表格中的行
            for cell in row.cells:  # 遍历行中的单元格
                for old, new in replacements.items():
                    if old in cell.text:  # 如果找到关键字
                        cell.text = cell.text.replace(old, new)  # 替换关键字
                        logging.info(f"Replaced '{old}' with '{new}' in表格 {docx_path}")
    doc.save(docx_path)  # 保存文档

def batch_replace_keywords(folder_path, replacements):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith(".docx"):
                docx_path = os.path.join(root, file)
                replace_keywords_in_docx(docx_path, replacements)

# 示例替换字典
replacements = {
    "旧关键字1": "新关键字1",
    "旧关键字2": "新关键字2",
}

# 批量替换D盘下的文档
batch_replace_keywords("D:\\目标文件夹", replacements)

源文件夹有如下文件:
有5个world文档,其中的host字需要批量替换成服务器
在这里插入图片描述
执行代码,后效果:先将代码里的字改成实际文档中的字,文件夹所在位置。
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
项目文件的日志里也有记录:
在这里插入图片描述
“三连本文,保你本季度KPI+50%!
不三连?小心下次改‘周末加班’为‘带薪休假’时代码报错哦~”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

技术职场教练

您的是我坚持原创免费作品的不懈

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值