pip install --index https://pypi.mirrors.ustc.edu.cn/simple/ python-office
二、pdf轉word2.1程式碼實作import office
office.pdf.pdf2docx(file_path = 'test.pdf')
運行過程如下:
[1/4]正在開啟文件...2.2 pdf內容[INFO][2/4]正在分析文件...
[警告]「建立」時間戳似乎很低;作為unix時間戳
[警告]「修改」時間戳似乎很低;作為unix時間戳
[警告]「創建」時間戳似乎非常低;作為unix時間戳
[警告]「修改」時間戳似乎很低;作為unix時間戳
[INFO] [3/4] 解析頁...
[INFO] (1/9) 第1頁
[INFO] (2/9) 第2頁
[訊息] (3/9) 第3 頁
[訊息] (4/9) 第4 頁
[訊息] (5/9) 第5 頁
[訊息] (6/9 ) 第6 頁
[INFO] (7/9) 第7頁
[INFO] (8/9) 第8頁
[INFO] (9/9) 第9頁
[ INFO] [4/4] 建立頁面...
[資訊] (1/9) 第1 頁
[資訊] (2/9) 第2 頁
[資訊] (3/9 ) 第3 頁
[訊息] (4 /9) 第4 頁
[訊息] (5/9) 第5 頁
[訊息] (6/9) 第6 頁
[訊息] (7/9) 第7 頁
[訊息] (8/9) 第8 頁
[訊息] (9/9) 第9 頁
[訊息] 在1.30 秒內終止。
進程已完成,退出程式碼為0
import os from configparser import ConfigParser from io import StringIO from io import open from concurrent.futures import ProcessPoolExecutor from pdfminer.pdfinterp import PDFResourceManager from pdfminer.pdfinterp import process_pdf from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from docx import Document def read_from_pdf(file_path): with open(file_path, 'rb') as file: resource_manager = PDFResourceManager() return_str = StringIO() lap_params = LAParams() device = TextConverter( resource_manager, return_str, laparams=lap_params) process_pdf(resource_manager, device, file) device.close() content = return_str.getvalue() return_str.close() return content def save_text_to_word(content, file_path): doc = Document() for line in content.split('\n'): paragraph = doc.add_paragraph() paragraph.add_run(remove_control_characters(line)) doc.save(file_path) def remove_control_characters(content): mpa = dict.fromkeys(range(32)) return content.translate(mpa) def pdf_to_word(pdf_file_path, word_file_path): content = read_from_pdf(pdf_file_path) save_text_to_word(content, word_file_path) def main(): config_parser = ConfigParser() config_parser.read('config.cfg') config = config_parser['default'] tasks = [] with ProcessPoolExecutor(max_workers=int(config['max_worker'])) as executor: for file in os.listdir(config['pdf_folder']): extension_name = os.path.splitext(file)[1] if extension_name != '.pdf': continue file_name = os.path.splitext(file)[0] pdf_file = config['pdf_folder'] + '/' + file word_file = config['word_folder'] + '/' + file_name + '.docx' print('正在处理: ', file) result = executor.submit(pdf_to_word, pdf_file, word_file) tasks.append(result) while True: exit_flag = True for task in tasks: if not task.done(): exit_flag = False if exit_flag: print('完成') exit(0) if __name__ == '__main__': main()方法二:加密過的PDF轉字
#-*- coding: UTF-8 -*- #!/usr/bin/python #-*- coding: utf-8 -*- import sys import importlib importlib.reload(sys) from pdfminer.pdfparser import PDFParser,PDFDocument from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import PDFPageAggregator from pdfminer.layout import * from pdfminer.pdfinterp import PDFTextExtractionNotAllowed import os #设置工作目录文件夹 os.chdir(r'c:/users/dicey/desktop/codes/pdf-docx') #解析pdf文件函数 def parse(pdf_path): fp = open('diya.pdf', 'rb') # 以二进制读模式打开 # 用文件对象来创建一个pdf文档分析器 parser = PDFParser(fp) # 创建一个PDF文档 doc = PDFDocument() # 连接分析器 与文档对象 parser.set_document(doc) doc.set_parser(parser) # 提供初始化密码 # 如果没有密码 就创建一个空的字符串 doc.initialize() # 检测文档是否提供txt转换,不提供就忽略 if not doc.is_extractable: raise PDFTextExtractionNotAllowed else: # 创建PDf 资源管理器 来管理共享资源 rsrcmgr = PDFResourceManager() # 创建一个PDF设备对象 laparams = LAParams() device = PDFPageAggregator(rsrcmgr, laparams=laparams) # 创建一个PDF解释器对象 interpreter = PDFPageInterpreter(rsrcmgr, device) # 用来计数页面,图片,曲线,figure,水平文本框等对象的数量 num_page, num_image, num_curve, num_figure, num_TextBoxHorizontal = 0, 0, 0, 0, 0 # 循环遍历列表,每次处理一个page的内容 for page in doc.get_pages(): # doc.get_pages() 获取page列表 num_page += 1 # 页面增一 interpreter.process_page(page) # 接受该页面的LTPage对象 layout = device.get_result() for x in layout: if isinstance(x,LTImage): # 图片对象 num_image += 1 if isinstance(x,LTCurve): # 曲线对象 num_curve += 1 if isinstance(x,LTFigure): # figure对象 num_figure += 1 if isinstance(x, LTTextBoxHorizontal): # 获取文本内容 num_TextBoxHorizontal += 1 # 水平文本框对象增一 # 保存文本内容 with open(r'test2.doc', 'a',encoding='utf-8') as f: #生成doc文件的文件名及路径 results = x.get_text() f.write(results) f.write('\n') print('对象数量:\n','页面数:%s\n'%num_page,'图片数:%s\n'%num_image,'曲线数:%s\n'%num_curve,'水平文本框:%s\n' %num_TextBoxHorizontal) if __name__ == '__main__': pdf_path = r'diya.pdf' #pdf文件路径及文件名 parse(pdf_path)
以上是怎麼用兩行Python程式碼實現pdf轉word功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

列表sandnumpyArraysInpythonHavedIfferentMemoryfootprints:listSaremoreFlexibleButlessMemory-效率,而alenumpyArraySareSareOptimizedFornumericalData.1)listsStorReereReereReereReereFerenceStoObjects,with withOverHeadeBheadaroundAroundaround64byty64-bitsysysysysysysysysyssyssyssyssysssyssys2)

toensurepythonscriptsbehavecorrectlyacrycrosdevelvermations,分期和生產,USETHESTERTATE:1)Environment varriablesForsimplesettings,2)configurationfilesfilesForcomPlexSetups,3)dynamiCofforComplexSetups,dynamiqualloadingForaptaptibality.eachmethodoffersuniquebeneiquebeneqeniquebenefitsandrefitsandrequiresandrequiresandrequiresca

Python列表切片的基本語法是list[start:stop:step]。 1.start是包含的第一個元素索引,2.stop是排除的第一個元素索引,3.step決定元素之間的步長。切片不僅用於提取數據,還可以修改和反轉列表。

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/刪除,2)儲存的二聚體和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,請考慮performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

禪工作室 13.0.1
強大的PHP整合開發環境