Python批量提取PDF文件中文本的脚本

yipeiwu_com6年前Python基础

本文实例为大家分享了Python批量提取PDF文件中文本的具体代码,供大家参考,具体内容如下

首先需要执行命令pip install pdfminer3k来安装处理PDF文件的扩展库。

import os
import sys
import time

pdfs = (pdfs for pdfs in os.listdir('.') if pdfs.endswith('.pdf'))

for pdf1 in pdfs:
 pdf = pdf1.replace(' ', '_').replace('-', '_').replace('&', '_')
 os.rename(pdf1, pdf)
 print('='*30)
 print(pdf)
 
 txt = pdf[:-4] + '.txt'
 exe = '"' + sys.executable + '" "'
 pdf2txt = os.path.dirname(sys.executable)
 pdf2txt = pdf2txt + '\\scripts\\pdf2txt.py" -o '
 try:
 #调用命令行工具pdf2txt.py进行转换
 #如果pdf加密过可以改写下面的代码
 #在-o前面使用-P来指定密码
 cmd = exe + pdf2txt + txt + ' ' + pdf
 os.popen(cmd)
 #转换需要一定时间,一般小文件2秒钟足够了
 time.sleep(2)
 #输出转换后的文本,前200个字符
 with open(txt, encoding='utf8') as fp:
  print(fp.read(200))
 except:
 pass

来源:python小屋

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python将文本去空格并保存到txt文件中的实例

如下所示: #encoding=utf-8# x=raw_input("Please enter a text: ") y=x.replace(" ","") f = open(...

使用python实现希尔、计数、基数基础排序的代码

使用python实现希尔、计数、基数基础排序的代码

希尔排序 希尔排序是一个叫希尔的数学家提出的一种优化版本的插入排序。 首先取一个整数d1=n//2,将元素分为d1个组,每组相邻元素之间的距离为d1,在各组内进行直接插入排序。 取第二个...

Python排序搜索基本算法之选择排序实例分析

Python排序搜索基本算法之选择排序实例分析

本文实例讲述了Python排序搜索基本算法之选择排序。分享给大家供大家参考,具体如下: 选择排序就是第n次把序列中最小的元素排在第n的位置上,一旦排好就是该元素的绝对位置。代码如下:...

Python中格式化format()方法详解

 Python中格式化format()方法详解 Python中格式化输出字符串使用format()函数, 字符串即类, 可以使用方法; Python是完全面向对象的语言, 任...

Python Tkinter 简单登录界面的实现

Python Tkinter 简单登录界面的实现

如下所示: from tkinter import * class Reg (Frame): def __init__(self,master): frame = F...