Python docx2txt库 Python中docx2txt库的使用教程

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python docx2txt库 Python中docx2txt库的使用教程

angus_monroe   2021-03-06 我要评论
想了解Python中docx2txt库的使用教程的相关内容吗,angus_monroe在本文为您仔细讲解Python docx2txt库的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python,docx2txt库,下面大家一起来学习吧。

docx2txt的Github地址

docx2txt是基于python的从docx文件中提取文本和图片的库。

代码是从python-docx中获取的。它也可以从页眉,页脚和超链接中提取文本。它现在也可以提取图像。

安装

pip install docx2txt

运行

1、命令行运行

# extract text
docx2txt file.docx
# extract text and images
docx2txt -i /tmp/img_dir file.docx

2、在python中调用

# extract text
docx2txt file.docx
# extract text and images
docx2txt -i /tmp/img_dir file.docx

补充:python docx提取word中的目录及文本框中的文本

问题描述

python docx提取word中的目录及文本框中的文本

解决方案

因未在docx库找到直接识别word中目录及文本框中文本的方法,所以采用了一个“笨”方法,docx库可以把word文档解析成xml格式,以解析xml的方式查找目录及文本框中文本,具体做法:

迭代出文档的所有element,其中目录的tag为“std”,找到它后提出他的所有文本即为目录文本;文本框的tag 为“textbox”,找到它后还要继续下钻寻找tag为 'r'的element,提取其文本则为文本框中文本。

# 提取word目录
file = docx.Document(file_path)
children = file.element.body.iter()
child_iters = []
for child in children:
 # 通过类型判断目录
 if child.tag.endswith('main}sdt'):
  for ci in child.iter():
   if ci.text and ci.text.strip():
    child_iters.append(ci)
catalog = [ci.text for ci in child_iters]
# 提取word文本框中文本
file = docx.Document(file_path)
children = file.element.body.iter()
child_iters = []
for child in children:
 # 通过类型判断目录
 if child.tag.endswith('textbox'):
  for ci in child.iter():
   if ci.tag.endswith('main}r'):
    child_iters.append(ci)
textbox = [ci.text for ci in child_iters]

文本域的标签,第一次找的是AlternateContent,后来发现对有些文本域失效;第二次又找到了pict,基本覆盖了测试的所有文本域;第三次把word文档的标签都找出来看了一下,发现textbox这个标签看着更靠谱,用它测试了一下,也能覆盖所有的测试文本域,决定就选择这个标签。

提取文本后,又有了新需求,提取的文本很多都不成句,呈短语或单词的形式,需要把提取的文本还原成段落形式:

file = docx.Document(file_path)
children = file.element.body.iter()
child_iters = []
tags = []
for child in children:
 # 通过类型判断目录
 if child.tag.endswith(('AlternateContent','textbox')):
  for ci in child.iter():
   tags.append(ci.tag)
   if ci.tag.endswith(('main}r', 'main}pPr')):
    child_iters.append(ci)
text = ['']
for ci in child_iters :
 if ci.tag.endswith('main}pPr'):
  text.append('')
 else:
  text[-1] += ci.text
 ci.text = ''
trans_text = ['***'+t+'***' for t in text]
print(trans_text)
i, k = 0, 0
for ci in child_iters :
 if ci.tag.endswith('main}pPr'):
  i += 1
  k = 0
 elif k == 0:
  ci.text = trans_text[i]
  k = 1
file.save('E:/***/test.docx')

把标签pPr当做换行标志, 把提取的文本每段前后都加了“***”后又写回文档中。

注:这里又发现AlternateContent这个标签必须要带上,否则可以提取文本域内的文字,但改变文字写回去保存word不显示更改后的文字。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们