Python读取pdf文件的简单代码示例

 更新时间:2024年02月18日 10:28:22   作者:JSON_L  
PDF文件的数据主要是文本、图片、表格,这三部分组成,但是也会穿插流程图、各种柱状图等,这篇文章主要给大家介绍了关于Python读取pdf文件的简单代码示例,需要的朋友可以参考下

安装命令

需要安装操作pdf的三方类库,命令如下:

pip install pdfminer3K

安装过程如下:

引入类库

需要引入很多的类库。

示例如下:

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 LTTextBoxHorizontal, LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed

读取pdf实现

实现步骤为:先通过二进制方式打开测试pdf文档,创建pdf文档解析测试文档内容,

最后读取文件内容,保存到另一个文件中。

示例如下:

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 LTTextBoxHorizontal, LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed
import os

def read_pdf(path, toPath):
    # 以二进制方式打开pdf文件
    f = open(path, 'rb')

    # 创建一个pdf文档分析器
    parser = PDFParser(f)
    # 创建pdf文档
    pdfFile = PDFDocument()
    # 链接分析器与文档对象
    parser.set_document(pdfFile)
    pdfFile.set_parser(parser)
    # 提供初始化密码
    pdfFile.initialize()

    # 检测文档是否提供txt转换
    if not pdfFile.is_extractable:
        raise PDFTextExtractionNotAllowed
    else:
        # 解析数据
        # 数据管理器
        manager = PDFResourceManager()
        # 创建一个PDF设备对象
        laparams = LAParams()
        device = PDFPageAggregator(manager, laparams=laparams)
        # 解释器对象
        interpreter = PDFPageInterpreter(manager, device)
        for page in pdfFile.get_pages():
            interpreter.process_page(page)
            layout = device.get_result()
            for x in layout:
                if isinstance(x, LTTextBoxHorizontal):
                    with open(toPath, 'a', encoding='utf-8') as f:
                        print(x.get_text())
                        f.write(x.get_text() + "\n")

path = os.path.join(os.getcwd(), 'test_1.pdf')
toPath = os.path.join(os.getcwd(), 'test_2.txt')
read_pdf(path, toPath)

注意:无法读取中文,貌似需要加载中文字体。还有就是在写入pdf文件,格式不对无法打开暂时没找到原因。

附:python读取PDF文件并做词云可视化

import pdfplumber  # 导入库
import jieba
from wordcloud import WordCloud
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
# 用pdf文件解析器读取文件
with pdfplumber.open('中华文化.pdf') as f:
    # 用for循环读取文件中的每一页
    for page in f.pages:
        text = page.extract_text()
        txt_f = open(r'中华文化.txt', mode='a', encoding='utf-8')  # 创建txt文件
        txt_f.write(text)  # 写入txt文件
 
file = open('中华文化.txt',encoding='utf-8')
file = file.read()  #读取txt文件
txtlist = jieba.lcut(file) 
string = " ".join(txtlist) 
stop_words = {}  
counts = {}  
for txt in txtlist:
    if len(txt) == 1:  
        stop_words[txt] = stop_words.get(txt, 0) + 1
    else:
        counts[txt] = counts.get(txt, 0) + 1 
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)  
y1 = []
labels = []
for i in range(1,10):
    y1.append(items[i][1])
    labels.append(items[i][0])
# plt.figure(figsize=(8,4))
width = 0.3
x = np.arange(len(y1))
a = [i for i in range(0,9)]
plt.xticks(a,labels,rotation = 30)
plt.bar(x=x,height=y1,width=width)
plt.title('PDF文件中热词统计分析')
plt.savefig("热词统计分析.png")
plt.show()
print("-------热词统计分析完成!-------")
stoplist=[]   
item = list(stop_words.items())
for i in range(len(item)): 
    txt,count = item[i]
    stoplist.append(txt)  
#print(stoplist)
setlist = set(stoplist)  
wcd = WordCloud(width=1000, height=700, background_color='white', font_path='msyh.ttc', scale=15, stopwords=setlist)
wcd.generate(string)
wcd.to_image()
print("-------热词词云生成完成!-------")
wcd.to_file('词云.png')  # 导出图片

总结

本篇只是使用Python 实现读取pdf文件简单示例,因为时间关系没有做深入的扩展,等之后有时间再做补充。

到此这篇关于Python读取pdf文件的文章就介绍到这了,更多相关Python读取pdf文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • celery在python爬虫中定时操作实例讲解

    celery在python爬虫中定时操作实例讲解

    在本篇文章里小编给大家整理了一篇关于celery在python爬虫中定时操作实例讲解内容,需要的朋友们可以参考下。
    2020-11-11
  • python中json格式处理和字典的关系

    python中json格式处理和字典的关系

    今天我们先讲一下编写python脚本处理json的核心功能,有些散乱,后期在进行整体脚本的编写,对python json字典关系相关知识感兴趣的朋友一起看看吧
    2022-06-06
  • Numpy中Meshgrid函数基本用法及2种应用场景

    Numpy中Meshgrid函数基本用法及2种应用场景

    NumPy包含很多实用的数学函数,涵盖线性代数运算、傅里叶变换和随机数生成等功能,下面这篇文章主要给大家介绍了关于Numpy中Meshgrid函数基本用法及2种应用场景的相关资料,需要的朋友可以参考下
    2022-08-08
  • Python+selenium实现截图图片并保存截取的图片

    Python+selenium实现截图图片并保存截取的图片

    这篇文章介绍如何利用Selenium的方法进行截图并保存截取的图片,需要的朋友参考下本文
    2018-01-01
  • Python发送邮件封装实现过程详解

    Python发送邮件封装实现过程详解

    这篇文章主要介绍了Python发送邮件封装实现过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-05-05
  • python能做哪方面的工作

    python能做哪方面的工作

    在本篇文章里我们给大家整理了关于学了python能做哪方面的工作的相关内容,有兴趣的朋友们可以学习下。
    2020-06-06
  • 使用selenium+chromedriver+xpath爬取动态加载信息

    使用selenium+chromedriver+xpath爬取动态加载信息

    这篇文章主要介绍了使用selenium+chromedriver+xpath爬取动态加载信息
    2022-02-02
  • Python实现EM算法实例代码

    Python实现EM算法实例代码

    这篇文章主要给大家介绍了关于Python实现EM算法的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-10-10
  • python实现简单五子棋小游戏

    python实现简单五子棋小游戏

    这篇文章主要为大家详细介绍了python实现简单五子棋小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-05-05
  • Python中使用pypdf2合并、分割、加密pdf文件的代码详解

    Python中使用pypdf2合并、分割、加密pdf文件的代码详解

    这篇文章主要介绍了Python中使用pypdf2合并、分割、加密pdf文件的代码,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-05-05

最新评论