您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:Python中docx2txt库的使用说明

51自学网 2021-10-30 22:53:13
  python
这篇教程Python中docx2txt库的使用说明写得很实用,希望能帮到您。

docx2txt的Github地址

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

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

安装

pip install docx2txt

运行

1、命令行运行

# extract textdocx2txt file.docx# extract text and imagesdocx2txt -i /tmp/img_dir file.docx

2、在python中调用

# extract textdocx2txt file.docx# extract text and imagesdocx2txt -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, 0for ci in child_iters : if ci.tag.endswith('main}pPr'):  i += 1  k = 0 elif k == 0:  ci.text = trans_text[i]  k = 1file.save('E:/***/test.docx')

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

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

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


python docx的超链接网址和链接文本操作
基于python goto的正确用法说明
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。