python通過docx模塊解決doc及docx後綴文件內容的處理
阿新 • • 發佈:2018-09-18
erb mpi dst mail 目錄 write exist lse patch
import os,shutil,docx,re,time
from win32com import client as wc
#從所有級聯目錄讀取文件到指定目錄內
def count_files(file_dir):
count=0
for p,d,f in os.walk(file_dir):
for c in f:
if c.split(‘.‘)[-1]=="doc":
count +=1
src_dir = os.path.join(p, c)
print(src_dir)
dst_dir = file_dir + "back"
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
shutil.copy(src_dir, dst_dir)
return count
#提取每個docx簡歷文檔裏面的郵箱地址,我們這裏使用python-docx模塊來解決pip install python-docx
def count_mail(file_dir,dst_file):
mail_list = []
for parent,dirctiory,files in os.walk(file_dir):
for f in files:
doc = docx.Document(os.path.join(parent,f))
pattern = re.compile(r‘‘‘([a-zA-Z0-9._%+-]+@[a-zA-Z0-9\t\s.-]+(\.[a-zA-Z0-9\t\s]{2,4}))‘‘‘, re.VERBOSE)
for para in doc.paragraphs:
for groups in pattern.findall(para.text):
mail_list.append(groups[0].replace(" ","")+";")
with open(dst_file,‘w‘)as f:
f.writelines(mail_list)
print("=====================郵件信息寫入成功===================")
#由於python-docx模塊只能處理docx後綴,我們需要處理doc後綴的文件,必須通過win32com模塊來把doc後綴轉換成docx
def docxTodoc(old_doc,new_doc):
word = wc.Dispatch(‘Word.Application‘)
for parent,directory,files in os.walk(old_doc):
for f in files:
doc = word.Documents.Open(os.path.join(parent,f)) # 目標路徑下的文件
new_filepath=os.path.join(new_doc,f.split(".")[0]+".docx")
print(new_filepath)
doc.SaveAs(new_filepath, 12, False, "", True, "", False, False, False,False) # 轉化後路徑下的文件
doc.Close()
print(time.time())
word.Quit()
if __name__ == ‘__main__‘:
print(count_files(r"C:\Users\icestick\Desktop\51job_導出簡歷_20180917"))
count_mail(r"C:\Users\icestick\Desktop\new_doc",r"C:\Users\icestick\Desktop\test.txt" )
old_doc = r"C:\Users\icestick\Desktop\51job_導出簡歷_20180917" #需要把doc目錄轉成docx格式的原目錄
new_doc = r"C:\Users\icestick\Desktop\new_doc" #需要把doc目錄轉成docx格式的目標目錄
mail_extract = r"C:\Users\icestick\Desktop\test.txt" #郵箱提取好的文件
if not os.path.exists(new_doc):
os.mkdir(new_doc)
print("=====================目錄創建成功======================")
docxTodoc(old_doc, new_doc)
print("=====================docx格式轉換成功===================")
count_mail(new_doc, mail_extract)
else:
docxTodoc(old_doc, new_doc)
print("=====================docx格式轉換成功===================")
count_mail(new_doc, mail_extract)
python通過docx模塊解決doc及docx後綴文件內容的處理