怎样用python实现将pdf转为word?一文教你四种办法
Admin 2021-08-25 群英技术资讯 3019 次浏览
这篇文章主要分享的是用python将pdf转为word文档的内容,下文提供了多种实现方法,具有一定借鉴价值,感兴趣的朋友可以参考下,感兴趣的朋友就继续往下看吧。
下面这个是最推荐的方法 ,简单高效 ,只要是标准PDF文档,里面的图片和表格都可以保留格式

# pip install pdf2docx #安装依赖库 from pdf2docx import Converter pdf_file = r'C:\Users\Administrator\Desktop\新建文件夹\mednine.pdf' docx_file = r'C:\Users\Administrator\Desktop\Python教程\02.docx' # convert pdf to docx cv = Converter(pdf_file) cv.convert(docx_file, start=0, end=None) cv.close()
1 把标准格式的PDF转为Word,测试环境Python3.6.5和3.6.6(注意PDF内容仅仅是文字为主的里面没有图片图表的适用,不适合扫描版PDF,因为那只能用图片识别的方式进行)
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO
import sys
import string
from docx import Document
def convert_pdf_2_text(path):
rsrcmgr = PDFResourceManager()
retstr = StringIO()
device = TextConverter(rsrcmgr, retstr, codec='utf-8', laparams=LAParams())
interpreter = PDFPageInterpreter(rsrcmgr, device)
with open(path, 'rb') as fp:
for page in PDFPage.get_pages(fp, set()):
interpreter.process_page(page)
#print(retstr.getvalue())
text = retstr.getvalue()
device.close()
retstr.close()
return text
def pdf2txt():
text=convert_pdf_2_text(path)
with open('real.txt','a',encoding='utf-8') as f:
for line in text.split('\n'):
f.write(line+'\n')
def remove_control_characters(content):
mpa = dict.fromkeys(range(32))
return content.translate(mpa)
def save_text_to_word(content, file_path):
doc = Document()
for line in content.split(''):
print(line)
paragraph = doc.add_paragraph()
paragraph.add_run(remove_control_characters(line))
doc.save(file_path)
if __name__ == '__main__':
path = r'C:\Users\mayn\Desktop\程序临时\培训教材.pdf' # 你自己的pdf文件路径及文件名 不适合扫描版 只适合标准PDF文件
text = convert_pdf_2_text(path)
save_text_to_word(text, 'output.doc') #PDF转为word方法
#pdf2txt() #PDF转为txt方法
2专门提取PDF里面的表格,使用pdfplumber适合标准格式的PDF
import pdfplumber
import pandas as pd
import time
from time import ctime
import psutil as ps
#import threading
import gc
pdf = pdfplumber.open(r"C:\Users\Administrator\Desktop\新建文件夹\mednine.pdf")
N=len(pdf.pages)
print('总共有',N,'页')
def pdf2exl(i): # 读取了第i页,第i页是有表格的,
print('*****************************************************************')
print('正在输出第',str(i+1),'页表格')
print('*****************************************************************')
p0 = pdf.pages[i]
try:
table = p0.extract_table()
print(table)
df = pd.DataFrame(table[1:], columns=table[0])
#print(df)
df.to_excel(r"C:\Users\Administrator\Desktop\新建文件夹\Model"+str(i+1)+".xlsx")
#df.info(memory_usage='deep')
except Exception as e:
print('第'+str(i+1)+'页无表格,或者检查是否存在表格')
pass
#print('目前内存占用率是百分之',str(ps.virtual_memory().percent),' 第',str(i+1),'页输出完毕')
print('********************************************************************')
print('\n\n\n')
time.sleep(5)
def dojob1(): #此函数 直接循环提取PDF里面各个页面的表格
print('*********************')
for i in range(0,N):
pdf2exl(i)
3也可以提取PDF里面的表格,使用camelot(camelot的安装可能需要点耐心,反正用的人不多)
import camelot
import wand
# 从PDF文件中提取表格
def output(i):
#print(tables)
#for i in range(5):
tables = camelot.read_pdf(r'C:\Users\Administrator\Desktop\新建文件夹\mednine.pdf', pages=str(i), flavor='stream')
print(tables[i])
# 表格数据
print(tables[i].data)
tables[i].to_csv(r'C:\Users\Administrator\Desktop\新建文件夹\002'+str(i)+r'.csv')
def plotpdf():
# 这个是画pdf 结构的函数 现在不能用 不要打开
#print(tables[0])
tables = camelot.read_pdf(r'C:\Users\mayn\Desktop\vcode工作区\11\路基.pdf', pages='200', flavor='stream')
camelot.plot(tables[0], kind='text')
print(tables[0])
plt.show()
# 绘制PDF文档的坐标,定位表格所在的位置
#plt = camelot.plot(tables[0],kind='text')
#plt.show()
#table_df = tables[0].df
#plotpdf()
#i=3
#output(i)
for i in range(0,2):
try:
output(i)
except Exception as e:
print('第'+str(i)+'页没找到表格啊啊啊')
pass
continue
以下是pdfplumber测试效果
源文件如下

提取结果

以上就是关于python实现pdf转为word稳定的方法介绍,上述代码仅供参考,希望能对大家有帮助,想要了解更多python实现pdf转为word的内容,大家可以关注其他相关文章。
文本转载自脚本之家
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
整个Spark 框架模块包含:Spark Core、 Spark SQL、 Spark Streaming、 Spark GraphX、 Spark MLlib,而后四项的能力都是建立在核心引擎之上。Spark Core:Spark的核心,Spark核心功能均由Spark Core模块提供...
占位符,顾名思义就是插在输出里站位的符号。占位符是绝大部分编程语言都存在的语法, 而且大部分都是相通的, 它是一种非常常用的字符串
多径效应(multipath effect):指电磁波经不同路径传播后,各分量场到达接收端时间不同,按各自相位相互叠加而造成干扰,使得原来的信号失真,或者产生错误。比如电磁波沿不同的两条路径传播,而两条路径的长度正好相差半个波长,那么两路信号到达终点时正好相互抵消了
很多新手学习python时,对于类的继承链理解比较困难,对此这篇文章就给大家分享python中类的继承链的内容。小编觉得挺实用的,大家可以参考参考,接下来一起跟随小编看看吧。
这篇文章主要为大家介绍了Keras利用efficientnet系列模型搭建yolov3目标检测平台的过程详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008