Python中docx2txt庫(kù)的使用說(shuō)明
docx2txt的Github地址
docx2txt是基于python的從docx文件中提取文本和圖片的庫(kù)。
代碼是從python-docx中獲取的。它也可以從頁(yè)眉,頁(yè)腳和超鏈接中提取文本。它現(xiàn)在也可以提取圖像。
安裝pip install docx2txt運(yùn)行1、命令行運(yùn)行
# extract textdocx2txt file.docx# extract text and imagesdocx2txt -i /tmp/img_dir file.docx2、在python中調(diào)用
# extract textdocx2txt file.docx# extract text and imagesdocx2txt -i /tmp/img_dir file.docx
補(bǔ)充:python docx提取word中的目錄及文本框中的文本
問(wèn)題描述python docx提取word中的目錄及文本框中的文本
解決方案因未在docx庫(kù)找到直接識(shí)別word中目錄及文本框中文本的方法,所以采用了一個(gè)“笨”方法,docx庫(kù)可以把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: # 通過(guò)類型判斷目錄 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: # 通過(guò)類型判斷目錄 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]
文本域的標(biāo)簽,第一次找的是AlternateContent,后來(lái)發(fā)現(xiàn)對(duì)有些文本域失效;第二次又找到了pict,基本覆蓋了測(cè)試的所有文本域;第三次把word文檔的標(biāo)簽都找出來(lái)看了一下,發(fā)現(xiàn)textbox這個(gè)標(biāo)簽看著更靠譜,用它測(cè)試了一下,也能覆蓋所有的測(cè)試文本域,決定就選擇這個(gè)標(biāo)簽。
提取文本后,又有了新需求,提取的文本很多都不成句,呈短語(yǔ)或單詞的形式,需要把提取的文本還原成段落形式:
file = docx.Document(file_path)children = file.element.body.iter()child_iters = []tags = []for child in children: # 通過(guò)類型判斷目錄 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’)
把標(biāo)簽pPr當(dāng)做換行標(biāo)志, 把提取的文本每段前后都加了“***”后又寫(xiě)回文檔中。
注:這里又發(fā)現(xiàn)AlternateContent這個(gè)標(biāo)簽必須要帶上,否則可以提取文本域內(nèi)的文字,但改變文字寫(xiě)回去保存word不顯示更改后的文字。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼2. 在Android中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解3. .NET中l(wèi)ambda表達(dá)式合并問(wèn)題及解決方法4. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法5. 淺談python出錯(cuò)時(shí)traceback的解讀6. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解7. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向8. Nginx+php配置文件及原理解析9. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析10. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題
