單位收集了很多word格式的調查表,領導需要收集表單里的信息,我就把所有調查表放一個文件里,寫了個python小程序把所需的信息打印出來
#coding:utf-8 import os import win32com from win32com.client import Dispatch, constants from docx import Document def parse_doc(f): """讀取doc,返回姓名和行業(yè) """ doc = w.Documents.Open( FileName = f ) t = doc.Tables[0] # 根據文件中的圖表選擇信息 name = t.Rows[0].Cells[1].Range.Text situation = t.Rows[0].Cells[5].Range.Text people = t.Rows[1].Cells[1].Range.Text title = t.Rows[1].Cells[3].Range.Text print name, situation, people,title doc.Close() def parse_docx(f): """讀取docx,返回姓名和行業(yè) """ d = Document(f) t = d.tables[0] name = t.cell(0,1).text situation = t.cell(0,8).text people = t.cell(1,2).text title = t.cell(1,8).text print name, situation, people,title if __name__ == "__main__": w = win32com.client.Dispatch('Word.Application') # 遍歷文件 PATH = "H:work\aaa" # windows文件路徑 doc_files = os.listdir(PATH) for doc in doc_files: if os.path.splitext(doc)[1] == '.docx': try: parse_docx(PATH+'\'+doc) except Exception as e: print e elif os.path.splitext(doc)[1] == '.doc': try: parse_doc(PATH+'\'+doc) except Exception as e: print e
希望本文所述對大家的Python程序設計有所幫助。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com