zoukankan      html  css  js  c++  java
  • 吴裕雄--天生自然python学习笔记:python文档操作批量替换 Word 文件中的文字

    我们经常会遇到在不同的 Word 文件中的需要做相同的文字替换,若是一个一个
    文件操作,会花费大量时间 。 本节案例可以找出指定目录中的所有 Word 文件(包含
    子目录),并对每一个文件进行指定的文字替换操作。
    案例要求
    把 replace 目录(包含子目录〉下所有 Word 文件中自甘“方法”都替换为“ method ”
    下图中左图为 replaces ubReplacee lse.docx 文件替换后的结果,右图为在命令窗口中
    显示的所有进行过替换操作的 Word 文件。
    import os
    from win32com import client
    from win32com.client import constants
    
    word = client.gencache.EnsureDispatch('Word.Application')
    word.Visible = 0
    word.DisplayAlerts = 0
    
    runpath = "F:\pythonBase\pythonex\ch08\replace"  #获取replace文件夹的路径
    tree = os.walk(runpath)  #取得目录树
    print("所有 Word 文件:")
    for dirname, subdir, files in tree:
        allfiles = []   
        for file in files:  # 取得所有.docx .doc文件,存入allfiles列表中
            ext = file.split(".")[-1]  #取得文件名后缀
            if((ext=="docx") or (ext=="doc")):  #取得所有.docx .doc文件
                allfiles.append(dirname + '\' + file)  #加入allfiles列表     
             
        if(len(allfiles) > 0):  #如果有符合条件的文件
            for dfile in allfiles:
                print(dfile)
                doc = word.Documents.Open(dfile)  #打开文件
                word.Selection.Find.ClearFormatting()
                word.Selection.Find.Replacement.ClearFormatting()
                word.Selection.Find.Execute("方法",False,False,False,False,False,True,constants.wdFindContinue,False,"method",constants.wdReplaceAll)
                doc.Close()
    word.Quit()

  • 相关阅读:
    APPIUM Android 定位方式
    SQL Server 根据存储过程的结果集创建临时表
    Ubuntu18.04 设置开机自启动服务
    ubuntu-18.04 (各版本镜像下载) 及的环境初始化配置
    CentOS 7 编译安装PHP5.6.31
    Centos7 编译安装 MySQL 5.5.62
    Windows 2008 R2 远程桌面连接记录(客户端IP)
    CentOS crontab定时任务
    CentOS 7 安装MySql 5.5.60
    SQL Server 数据库错误码解释
  • 原文地址:https://www.cnblogs.com/tszr/p/12030531.html
Copyright © 2011-2022 走看看