Python中docx2txt庫的使用說明
docx2txt是基于python的從docx文件中提取文本和圖片的庫。
代碼是從python-docx中獲取的。它也可以從頁眉,頁腳和超鏈接中提取文本。它現(xiàn)在也可以提取圖像。
安裝
pip install docx2txt
運行
1、命令行運行
# extract text docx2txt file.docx # extract text and images docx2txt -i /tmp/img_dir file.docx
2、在python中調(diào)用
# 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”,找到它后還要繼續(xù)下鉆尋找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,后來發(fā)現(xiàn)對有些文本域失效;第二次又找到了pict,基本覆蓋了測試的所有文本域;第三次把word文檔的標簽都找出來看了一下,發(fā)現(xiàn)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當做換行標志, 把提取的文本每段前后都加了“***”后又寫回文檔中。
注:這里又發(fā)現(xiàn)AlternateContent這個標簽必須要帶上,否則可以提取文本域內(nèi)的文字,但改變文字寫回去保存word不顯示更改后的文字。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Pytorch如何指定device(cuda or cpu)
這篇文章主要介紹了Pytorch如何指定device(cuda or cpu)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
Pytorch中的modle.train,model.eval,with torch.no_grad解讀
這篇文章主要介紹了Pytorch中的modle.train,model.eval,with torch.no_grad解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
使用python爬取微博數(shù)據(jù)打造一顆“心”
這篇文章主要介紹了使用python基于微博數(shù)據(jù)打造一顆“心”,作為程序員,我準備了一份特別的禮物,用以往發(fā)的微博數(shù)據(jù)打造一顆“愛心”,我想她一定會感動得哭了吧,需要的朋友可以參考下2019-06-06

