使用BAT批处理加PYTHON进行WORD批量文字删除

使用BAT批处理加PYTHON进行WORD批量文字删除,需要删除的文字存放在txt中,编码为UTF-8,文件名为remove_words.txt

安装pip install python-docxpip install chardet

remove_text.py代码

复制代码
import os
import chardet
from docx import Document

def remove_text_from_docx(docx_path, text_list):
    doc = Document(docx_path)
    for paragraph in doc.paragraphs:
        for text in text_list:
            if text in paragraph.text:
                paragraph.text = paragraph.text.replace(text, '')
    doc.save(docx_path)

def main(txt_path, docx_folder):
    try:
        # 检测文件编码
        with open(txt_path, 'rb') as f:
            raw_data = f.read()
            result = chardet.detect(raw_data)
            encoding = result['encoding']

        with open(txt_path, 'r', encoding=encoding) as f:
            text_list = [line.strip() for line in f.readlines()]
    except Exception as e:
        print(f"Error reading txt file: {e}")
        return
    if not os.path.isdir(docx_folder):
        print(f"Error: The docx folder {docx_folder} does not exist.")
        return
    try:
        for root, dirs, files in os.walk(docx_folder):
            for file in files:
                if file.endswith('.docx'):
                    docx_path = os.path.join(root, file)
                    print(f"Processing file: {docx_path}")
                    remove_text_from_docx(docx_path, text_list)
    except Exception as e:
        print(f"Error processing docx files: {e}")

if __name__ == "__main__":
    import sys
    try:
        if len(sys.argv) != 3:
            print("Usage: python remove_text.py <txt_path> <docx_folder>")
        else:
            txt_path = sys.argv[1]
            docx_folder = sys.argv[2]
            main(txt_path, docx_folder)
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

bat代码

复制代码
@echo off
chcp 65001 
setlocal enabledelayedexpansion

rem 修改为实际的 txt 文件路径
set txt_path=C:\Users\Admin\Desktop\remove_words.txt
rem 修改为实际的 docx 文件所在文件夹路径
set docx_folder=C:\Users\Admin\Desktop\文档
rem python.exe的位置
set python_path=C:\Users\Admin\AppData\Local\Programs\Python\Python313\python.exe

%python_path% C:\Users\Admin\Desktop\remove_text.py %txt_path% %docx_folder%

pause>nul
endlocal

请使用管理员权限运行BAT

支持通配符版本如下

复制代码
@echo off
setlocal enabledelayedexpansion

rem 修改为实际的 txt 文件路径
set txt_path=路径
rem 使用通配符指定 docx 文件所在的文件夹模式
set docx_folder_pattern=路径*

set python_path=路径

echo "Python path: %python_path%"
echo "Txt file path: %txt_path%"
echo "Docx folder pattern: %docx_folder_pattern%"

%python_path% 路径\remove_text.py %txt_path% "%docx_folder_pattern%"

endlocal

import os
import chardet
import glob
from docx import Document

def remove_text_from_docx(docx_path, text_list):
    doc = Document(docx_path)
    for paragraph in doc.paragraphs:
        for text in text_list:
            if text in paragraph.text:
                paragraph.text = paragraph.text.replace(text, '')
    doc.save(docx_path)

def main(txt_path, docx_folder_pattern):
    try:
        # 检测文件编码
        with open(txt_path, 'rb') as f:
            raw_data = f.read()
            result = chardet.detect(raw_data)
            encoding = result['encoding']

        with open(txt_path, 'r', encoding=encoding) as f:
            text_list = [line.strip() for line in f.readlines()]
    except Exception as e:
        print(f"Error reading txt file: {e}")
        return

    docx_files = glob.glob(os.path.join(docx_folder_pattern, '*.docx'))
    if not docx_files:
        print(f"No docx files found matching the pattern: {docx_folder_pattern}")
        return

    for docx_path in docx_files:
        try:
            print(f"Processing file: {docx_path}")
            remove_text_from_docx(docx_path, text_list)
        except Exception as e:
            print(f"Error processing {docx_path}: {e}")

if __name__ == "__main__":
    import sys
    try:
        if len(sys.argv) != 3:
            print("Usage: python remove_text.py <txt_path> <docx_folder_pattern>")
        else:
            txt_path = sys.argv[1]
            docx_folder_pattern = sys.argv[2]
            main(txt_path, docx_folder_pattern)
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
相关推荐
和鲸社区10 分钟前
《斯坦福CS336》作业1开源,从0手搓大模型|代码复现+免环境配置
人工智能·python·深度学习·计算机视觉·语言模型·自然语言处理·nlp
豌豆花下猫42 分钟前
Python 潮流周刊#118:Python 异步为何不够流行?(摘要)
后端·python·ai
THMAIL1 小时前
深度学习从入门到精通 - LSTM与GRU深度剖析:破解长序列记忆遗忘困境
人工智能·python·深度学习·算法·机器学习·逻辑回归·lstm
wheeldown1 小时前
【数学建模】数据预处理入门:从理论到动手操作
python·数学建模·matlab·python3.11
多打代码2 小时前
2025.09.05 用队列实现栈 & 有效的括号 & 删除字符串中的所有相邻重复项
python·算法
@CLoudbays_Martin112 小时前
为什么动态视频业务内容不可以被CDN静态缓存?
java·运维·服务器·javascript·网络·python·php
IT小农工2 小时前
Windows 文件资源管理器无法预览文件内容word、ppt、excel、pdf
windows·word·powerpoint
程序猿炎义2 小时前
【NVIDIA AIQ】自定义函数实践
人工智能·python·学习
BillKu2 小时前
在 Delphi 5 中获取 Word 文档页数的方法
word·delphi
THMAIL3 小时前
深度学习从入门到精通 - BERT与预训练模型:NLP领域的核弹级技术详解
人工智能·python·深度学习·自然语言处理·性能优化·bert