栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 读取office 文件基础--- docx

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 读取office 文件基础--- docx

从office2007开始,微软采用ZIP压缩技术来存储文档Office Open XML格式。例如 word采用的docx就是一个zip压缩包,里面保存了以xml为主的文件。

读取docx文件示例如下:

from zipfile import ZipFile
from bs4 import BeautifulSoup

#1 使用zip解压docx,解析 document.xml 提取所有页docx文字」
def ReadDocxXmlContent(srcDocxFile ):
      text = ""      
      with ZipFile(srcDocxFile) as zf:
          xmldoc= zf.read('word/document.xml').decode()
          soup = BeautifulSoup(xmldoc, 'xml')

         #主体节点
          phaseList =  soup.find('w:body')       
          for child in phaseList.children:             
             
             #1 处理表格内容
             if child.name == 'tbl' :
                  for sub_child in child.children:
                      if sub_child.name == 'tr':
                          item_tr = sub_child.find_all('w:t' ) 
                          temptxt = ''              
                          for sub_item in item_tr:
                              
                              temptxt =temptxt+ sub_item.getText()
                         
                          text = text  + temptxt
                          text = text  +'n'
                  
             #2 处理普通段落
             #if child.name == 'p':
             else:
                  item_tr = child.find_all('w:t' ) 
                  temptxt = ''              
                  for sub_item in item_tr:                      
                      temptxt =temptxt+ sub_item.getText()
                  
                  text = text  + temptxt
                  text = text  +'n'
              
      return text

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/739943.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号