環境要求:Python3.6 ; pycharmIDE ;anacondapython
須要插件:win32comapp
ps:建議使用---->在cmd中使用python -m pip install pypiwin32進行安裝工具
# coding=utf-8 import os, fnmatch # fnmatch 匹配後綴名的包 from win32com import client as wc from win32com.client import Dispatch, gencache def Files2txt(filePath, savePath=''): try: # 切分文件目錄和文件名 dirs, filename = os.path.split(filePath) # 修改轉化後的文件名 typename = os.path.splitext(filename)[-1].lower() new_name = TranType(filename, typename) # 文件轉化後的保存路徑 if savePath == '': savePath = dirs else: savePath = savePath new_save_path = os.path.join(savePath, new_name) print('保存路徑:', new_save_path) # 加載處理應用 manyapp = wc.Dispatch('Word.Application') mytxt = manyapp.Documents.Open(filePath) mytxt.SaveAs(new_save_path, 4) mytxt.Close() print('處理完成,請查看!') except Exception as e: print('程序出錯了!') def TranType(filename, typename): ''' 根據文件後綴修改文件名 一、文件名 二、文件類型後綴 返回修改後的新的文件名 ''' new_name = '' if typename == '.pdf': if fnmatch.fnmatch(filename, '*.pdf'): new_name = filename[:-4] + '.txt' else: return elif typename == '.doc' or typename == '.docx': if fnmatch.fnmatch(filename, '*.doc'): new_name = filename[:-4] + '.txt' elif fnmatch.fnmatch(filename, '*.docx'): new_name = filename[:-5] + '.txt' else: return else: print('警告:\n 您輸入【', typename, '】不合法,工具僅支持pdf/doc/docx格式,請輸入正確的格式。') return return new_name if __name__ == '__main__': filepath1 = os.path.abspath(r'D:\Python\study\test\抽取文本信息\智聯範本.docx') Files2txt(filepath1)
未完待續...spa