温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

docx2txt库怎么在Python中使用

发布时间:2021-03-08 11:21:15 来源:亿速云 阅读:485 作者:Leah 栏目:开发技术

这期内容当中小编将会给大家带来有关docx2txt库怎么在Python中使用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

Python主要用来做什么

Python主要应用于:1、Web开发;2、数据科学研究;3、网络爬虫;4、嵌入式应用开发;5、游戏开发;6、桌面应用开发。

安装

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')

上述就是小编为大家分享的docx2txt库怎么在Python中使用了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI