”阅读此篇需要三分钟“

首先来看看来个PDF文件

我们来选择其中一个论文摘要:

使用我们的python代码转化后:

是不是很神奇?

现在网络上大部分的PDF转Word都是收费的,基本都是按页收费,有了我们的python代码后,我们就可以完全免费的将PDF转成Word了,这么好的福利我们赶紧来了解一下吧!

首先来看看我们要安装一些什么模块:

attrs==17.4.0

lxml==4.1.1

pdfminer3k==1.3.1

pluggy==0.6.0

ply==3.11

py==1.5.2

pytest==3.4.1

python-docx==0.8.6

six==1.11.0

使用pip模块管理工具即可安装。

如上图,将每个模块都安装好。

或者直接将模块放到requirements.txt文件里,运行

pip install -r requirements

安装即可

下一步就来开始coding了!

首先导入需要使用的模块:

import os

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

然后定义好PDF文件的读取路径和Word文件的生成路径。

pdf_folder = r'/Users/wuyuqing/Desktop/Code/pdf2word/pdf'

word_folder = r'/Users/wuyuqing/Desktop/Code/pdf2word/word'

接下来我们定义使用的方法:

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

通过字节流的方式打开文件,读取内容。我们主要使用process_pdf这个函数处理pdf,详情处理步骤我们可以看看API是这么处理的(这API写好的代码,供参考,不需要你再次手写):

def process_pdf(rsrcmgr, device, fp, pagenos=None, maxpages=0, password='',

caching=True, check_extractable=True):

# Create a PDF parser object associated with the file object.

parser = PDFParser(fp)

# Create a PDF document object that stores the document structure.

doc = PDFDocument(caching=caching)

# Connect the parser and document objects.

parser.set_document(doc)

doc.set_parser(parser)

# Supply the document password for initialization.

# (If no password is set, give an empty string.)

doc.initialize(password)

# Check if the document allows text extraction. If not, abort.

if check_extractable and not doc.is_extractable:

raise PDFTextExtractionNotAllowed(

'Text extraction is not allowed: %r' % fp)

# Create a PDF interpreter object.

interpreter = PDFPageInterpreter(rsrcmgr, device)

# Process each page contained in the document.

for (pageno,page) in enumerate(doc.get_pages()):

if pagenos and (pageno not in pagenos): continue

interpreter.process_page(page)

if maxpages and maxpages <= pageno+1: break

下面我们考虑将字节流存成docx文档:

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 pdf_to_word(pdf_file_path, word_file_path):

content = read_from_pdf(pdf_file_path)

save_text_to_word(content, word_file_path)

主要功能完成,这样就算完工了

下面我们来调用读取pdf生成docx的方法

tasks = []

with ProcessPoolExecutor(max_workers=5) as executor:

for file in os.listdir(pdf_folder):

extension_name = os.path.splitext(file)[1]

if extension_name != '.pdf':

continue

file_name = os.path.splitext(file)[0]

pdf_file = pdf_folder + '/' + file

word_file = 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)

这样就可以生成doc文件了,怎么样是不是很简单?

python读取pdf内容转word_Python实现PDF转Word相关推荐

  1. python中读取文件内容-Python读取文件内容的三种常用方式及效率比较

    本文实例讲述了Python读取文件内容的三种常用方式.分享给大家供大家参考,具体如下: 本次实验的文件是一个60M的文件,共计392660行内容. 程序一: def one(): start = ti ...

  2. python怎么读文件内容-Python读取文件内容为字符串的方法(多种方法详解)

    以下笔记是我在 xue.cn 学习群之数据分析小组所整理分享的心得.相关背景是:我选择中文词频统计案例作为考察大家python基础功掌握程度. 以小见大,下面是2个小技能的具体实战: 如何灵活地处理文 ...

  3. python火狐配置文件_Python+Selenium中级篇之4-封装一个自己的类-浏览器引擎类/Python读取配置文件内容...

    封装一个自己的类-浏览器引擎类 前一篇文章我们知道了,如何去封装几个简单的Selenium方法到我们自定义的类,这次我们编写一个类,叫浏览器引擎类,通过更改一个字符串的值,利用if语句去判断和控制启动 ...

  4. 可免费编辑 PDF 内容的 7 大 PDF 编辑工具

    有时您可能希望编辑 PDF 文档中的敏感信息,例如财务帐号和 ID 号,以便在不泄露隐私的情况下共享 PDF.编辑 PDF 是从 PDF 中删除私有内容.使用PDF 编辑工具可以轻松完成编辑.市场上有 ...

  5. Python读取文件内容为字符串的方法(多种方法详解)

    方法1: 拷贝文章时,直接把内容赋值给一个变量,保存到一个 .py 文件中.然后在脚本中,导入它. 存储文章的文件article.py content = """ 复制的 ...

  6. python 读取发票内容,在窗口中显示并保存到excel文件中

    编写两个文件ReadPdf.py和QTShow.py ReadPdf.py 1.采用正则表达式re定义提取的字段:(目前只读取这8个字段,开户行及账户在测试中出现问题) self.template_f ...

  7. python中读取文件内容-Python读取文件内容与存储

    Python读取与存储文件内容 一..csv文件 读取: importpandas as pd souce_data= pd.read_csv(File_Path) 其中File_path是文件的路径 ...

  8. python读取文件内容-Python读取文件内容与存储

    Python读取与存储文件内容 一..csv文件 读取: importpandas as pd souce_data= pd.read_csv(File_Path) 其中File_path是文件的路径 ...

  9. python读取文件内容并操作_Python实现的读取文件内容并写入其他文件操作示例

    本文实例讲述了Python实现的读取文件内容并写入其他文件操作.分享给大家供大家参考,具体如下: 文件目录结构,如图: read_file.py是工作文件,file_test.py是读取文件源,wri ...

最新文章

  1. python自动办公 pdf_Python办公自动化|批量合并PDF,拿来就用
  2. Python天天美味(5) - ljust rjust center
  3. UVA 331 Mapping the Swaps
  4. The method getTextContent() is undefined ?
  5. python socks5 代理服务
  6. SAP S/4HANA生产订单释放后自动同步到MES系统
  7. sympy科学计算器
  8. Nginx 反向代理 websocket 协议
  9. 从拉格朗日乘数法到KKT条件
  10. Crusher Django 学习笔记4 使用Model
  11. 电子游戏跟计算机有什么关联,电脑和电子游戏对小学生的影响
  12. 夺命雷公狗---javascript NO:19 Navigator浏览器对象
  13. [蓝桥杯]基础练习 回文数
  14. 解决升级Win 10 IP 10122后无法调试UAP应用的方法
  15. java switch命令_Java switch-case语句用法
  16. 通用html解析器,razor-从外部存储的.cshtml解析Rarzor HTML帮助器
  17. 第六天:对项目后端日志存储
  18. Spring Boot消息服务
  19. 怎样理解OOP?OOP又是什么?
  20. 华东理工大计算机专业,华东理工大学计算机专业怎么样(计算机专业大学排名50)...

热门文章

  1. Python多分支、循环
  2. 【编码推流】安装VPF-20210222视频处理框架-补充1
  3. Python数据分析宝藏地带
  4. 消防通信有哪些解决方案?
  5. C#关于打印90度转换
  6. linux系统读sim卡信息,在Linux下使用串口读取SIM卡上的SMS消息使用C
  7. 【淘宝开店教程】教你借618大促打造店铺爆款宝贝
  8. 电商大促攻略页设计指南
  9. 漫画插画培训网课排行榜
  10. JAVA day07:代码作业(继承)