欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

【Python】Docx解析

发布时间:2024/4/14 50 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【Python】Docx解析 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

1、cd D:\ProgramData\Anaconda3

2、pip install python-docx

3、python代码处理

# -*- coding: utf-8 -*-import os import docx from win32com import client as wcdocs = []def traverse(f):fs = os.listdir(f)for f1 in fs:tmp_path = os.path.join(f,f1)if not os.path.isdir(tmp_path):#print('文件: %s'%tmp_path)if os.path.splitext(tmp_path)[-1].lower() == ".doc" or os.path.splitext(tmp_path)[-1].lower() == ".docx":#print('文件: %s'%tmp_path) docs.append(tmp_path)else:#print('文件夹:%s'%tmp_path) traverse(tmp_path)def parseDoc(f):doc = docx.Document(f)parag_num = 0for para in doc.paragraphs :print("----------------------------------------------------")print(para.text)print("----------------------------------------------------")parag_num += 1 print ('This document has ', parag_num, ' paragraphs')def doc2docx(full_path):#dirname = os.path.dirname(full_path)#filename = os.path.basename(full_path)#newpath = full_path.replace('doc','docx')newpath = full_path + "x"if os.path.exists(newpath):return# 首先将doc转换成docxword = wc.Dispatch("Word.Application")# 找到word路径 + 文件名 ,即可打开文件 doc = word.Documents.Open(full_path)# 使用参数16表示将doc转换成docx,保存成docx后才能 读文件doc.SaveAs(newpath,16)doc.Close()word.Quit()path = 'E:/NLP/Docs/'traverse(path)for k,v in enumerate(docs):if k < 1:print(k,v)parseDoc(v)#doc2docx(v)

 

总结

以上是生活随笔为你收集整理的【Python】Docx解析的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。