基于python的PDF文件解析器汇总

基于python的PDF文件解析器汇总

大多数已发表的科学文献目前以 PDF 格式存在,这是一种轻量级、普遍的文件格式,能够保持一致的文本布局和格式。对于人类读者而言, PDF格式的文件内容展示整洁且一致的布局有助于阅读,可以很容易地浏览一篇论文并识别标题和图表。但是对于计算机而言,PDF 格式是一个非常嘈杂的 ASCII 文件,并不包含任何结构化文本的信息。因此,我们期望从这些已经发表的PDF格式科学文献中重新提取文字、图片、表格、注释、目录等数据来构建格式化的信息用于机器学习,例如目前最需要大量文本数据的自然语言处理(Natural Language Processing, NLP)或大语言模型(Large Language Modles ,LLMs)等应用中。


1. Nougat

Nougat (Neural Optical Understanding for Academic Documents)是Meta出品的一款基于ViT(Visual Transformer)的模型,通过光学字符识别(Optical Character Recognition, OCR)将科学论文转化为标记语言。

  • 最新发布时间:2023年8月22日

  • GitHub address: GitHub - facebookresearch/nougat: Implementation of Nougat Neural Optical Understanding for Academic Documents

  • Project page: Nougat

1.1 安装

安装之前的一些依赖与要求如下:

python_requires=“>=3.7”,
“transformers=4.38.2”,
“timm==0.5.4”,
“orjson”,
“opencv-python-headless”,
“datasets[vision]”,
“lightning>=2.0.0,<2022”,
“nltk”,
“python-Levenshtein”,
“sentencepiece”,
“sconf>=0.2.3”,
“albumentations>=1.0.0”,
“pypdf>=3.1.0”,
“pypdfium2”

安装:

#创建一个新环境
conda create -n nougat python=3.9
#激活该环境
conda activate nougat# from pip:
pip install nougat-ocr# or from github repository
pip install git+https://github.com/facebookresearch/nougat

1.2 测试

nougat path/to/file.pdf --out output_directory

1.3 用法

usage: nougat [-h] [--batchsize BATCHSIZE] [--checkpoint CHECKPOINT] [--model MODEL] [--out OUT][--recompute] [--markdown] [--no-skipping] pdf [pdf ...]positional arguments:pdf                   PDF(s) to process.options:-h, --help            show this help message and exit--batchsize BATCHSIZE, -b BATCHSIZEBatch size to use.--checkpoint CHECKPOINT, -c CHECKPOINTPath to checkpoint directory.--model MODEL_TAG, -m MODEL_TAGModel tag to use.--out OUT, -o OUT     Output directory.--recompute           Recompute already computed PDF, discarding previous predictions.--full-precision      Use float32 instead of bfloat16. Can speed up CPU conversion for some setups.--no-markdown         Do not add postprocessing step for markdown compatibility.--markdown            Add postprocessing step for markdown compatibility (default).--no-skipping         Don't apply failure detection heuristic.--pages PAGES, -p PAGESProvide page numbers like '1-4,7' for pages 1 through 4 and page 7. Only works 

1.4 优劣限制

    1. Nougat模型的训练数据几乎全是英文文献,因此对非英文文字的识别有待考证。特别是中文与英文和拉丁文体相差较大,因此中文文献的识别准确率很差,几乎不能用。
    1. 依旧是训练数据,训练数据全部为科学论文(来自于arXiv、PMC和IDL),因此对科学论文的识别精度较高,除此之外的PDF文档的识别效率依旧有待考证和进一步的优化。
    1. 由于这种方法是基于深度学习算法,因此在识别PDF文档时不可避免的需要使用GPU算力,且通常比经典方法(GROBID )要慢。

2. ScienceBeam Parser

  • Githu address:ScienceBeam

2.1 安装

pip install sciencebeam-parser

2.2 测试

Python API: 服务器启动

from sciencebeam_parser.config.config import AppConfig
from sciencebeam_parser.resources.default_config import DEFAULT_CONFIG_FILE
from sciencebeam_parser.service.server import create_appconfig = AppConfig.load_yaml(DEFAULT_CONFIG_FILE)
app = create_app(config)
app.run(port=8080, host='127.0.0.1', threaded=True)

Python API: 解析PDF文件

from sciencebeam_parser.resources.default_config import DEFAULT_CONFIG_FILE
from sciencebeam_parser.config.config import AppConfig
from sciencebeam_parser.utils.media_types import MediaTypes
from sciencebeam_parser.app.parser import ScienceBeamParserconfig = AppConfig.load_yaml(DEFAULT_CONFIG_FILE)# the parser contains all of the models
sciencebeam_parser = ScienceBeamParser.from_config(config)# a session provides a scope and temporary directory for intermediate files
# it is recommended to create a separate session for every document
with sciencebeam_parser.get_new_session() as session:session_source = session.get_source('example.pdf',MediaTypes.PDF)converted_file = session_source.get_local_file_for_response_media_type(MediaTypes.TEI_XML)# Note: the converted file will be in the temporary directory of the sessionprint('converted file:', converted_file)

3. pdfrw

3.1 安装

pip install pdfrw

3.2 测试

from pdfrw import PdfReader
def get_pdf_info(path):pdf = PdfReader(path)print(pdf.keys())print(pdf.Info)print(pdf.Root.keys())print('PDF has {} pages'.format(len(pdf.pages)))if __name__ == '__main__':get_pdf_info('example.pdf')

4. PDFQuery

4.1 安装

pip install pdfquery

4.2 测试

from pdfquery import PDFQuerypdf = PDFQuery('example.pdf')
pdf.load()# Use CSS-like selectors to locate the elements
text_elements = pdf.pq('LTTextLineHorizontal')# Extract the text from the elements
text = [t.text for t in text_elements]print(text)

5. pdfminer.six

  • GitHub address:pdfminer.six

  • 最新发布时间:2023年12月28日

5.1 安装

pip install pdfminer.six

5.2 测试

from pdfminer.high_level import extract_texttext = extract_text("example.pdf")
print(text)

5.3 功能

  • 支持各种字体类型(Type1、TrueType、Type3 和 CID)。
  • 支持提取图像(JPG、JBIG2、Bitmaps)。
  • 支持各种压缩方式(ASCIIHexDecode、ASCII85Decode、LZWDecode、FlateDecode、RunLengthDecode、CCITTFaxDecode)。
  • 支持 RC4 和 AES 加密。
  • 支持提取 AcroForm 交互式表单。
  • 提取目录。
  • 提取标记内容。
  • 自动布局分析。

6. SciPDF Parser

基于GROBID (GeneRation Of BIbliographic Data))

  • Github address: SciPDF Parser

  • 最新发布时间:

6.1 安装

# from pip
pip install scipdf-parser# or from github respository
pip install git+https://github.com/titipata/scipdf_parser

6.2 测试

在解析PDF之前需要先运行GROBID

bash serve_grobid.sh

该脚本将会运行 GROBID在默认端口:8070
以下为python 解析PDF文件的脚本。

import scipdf
article_dict = scipdf.parse_pdf_to_dict('example_data/futoma2017improved.pdf') # return dictionary# option to parse directly from URL to PDF, if as_list is set to True, output 'text' of parsed section will be in a list of paragraphs instead
article_dict = scipdf.parse_pdf_to_dict('https://www.biorxiv.org/content/biorxiv/early/2018/11/20/463760.full.pdf', as_list=False)# output example
>> {'title': 'Proceedings of Machine Learning for Healthcare','abstract': '...','sections': [{'heading': '...', 'text': '...'},{'heading': '...', 'text': '...'},...],'references': [{'title': '...', 'year': '...', 'journal': '...', 'author': '...'},...],'figures': [{'figure_label': '...', 'figure_type': '...', 'figure_id': '...', 'figure_caption': '...', 'figure_data': '...'},...],'doi': '...'
}xml = scipdf.parse_pdf('("example.pdf', soup=True) # option to parse full XML from GROBID

7. pdfplumber

  • GitHub address: pdfplumber

  • 最新发布时间:2024年3月7日

7.1 安装

pip install pdfplumber

7.2 测试

pdfplumber < example.pdf > background-checks.csv

7.3 用法

参数描述
--format [format]csv or json. The json format returns more information; it includes PDF-level and page-level metadata, plus dictionary-nested attributes.
--pages [list of pages]A space-delimited, 1-indexed list of pages or hyphenated page ranges. E.g., 1, 11-15, which would return data for pages 1, 11, 12, 13, 14, and 15.
--types [list of object types to extract]Choices are char, rect, line, curve, image, annot, et cetera. Defaults to all available.
--laparamsA JSON-formatted string (e.g., '{"detect_vertical": true}') to pass to pdfplumber.open(..., laparams=...).
--precision [integer]The number of decimal places to round floating-point numbers. Defaults to no rounding.

7.4 python package usage

import pdfplumberwith pdfplumber.open("example.pdf") as pdf:first_page = pdf.pages[0]print(first_page.chars[0])

8. borb

8.0 简介

borb 是一个纯 Python 库,用于读取、写入和操作 PDF 文档。它将 PDF 文档表示为嵌套列表、字典和基本数据类型(数字、字符串、布尔值等)的类似 JSON 的数据结构。

  • Github address: borb

  • 最新发布时间:2024年5月

8.1 安装

  • 下载地址: borb · PyPI
# from pip
pip install borb# reinstalled the latest version (rather than using its internal cache)
pip uninstall borb
pip install --no-cache borb

8.2 测试(创建pdf)

from pathlib import Pathfrom borb.pdf import Document
from borb.pdf import Page
from borb.pdf import SingleColumnLayout
from borb.pdf import Paragraph
from borb.pdf import PDF# create an empty Document
pdf = Document()# add an empty Page
page = Page()
pdf.add_page(page)# use a PageLayout (SingleColumnLayout in this case)
layout = SingleColumnLayout(page)# add a Paragraph object
layout.add(Paragraph("Hello World!"))# store the PDF
with open(Path("output.pdf"), "wb") as pdf_file_handle:PDF.dumps(pdf_file_handle, pdf)

8.3 功能

  • 读取PDF并提取元信息
  • 修改元信息
  • 从PDF中提取文本
  • 从PDF中提取图像
  • 改变PDF中的图像
  • 向PDF添加注释(笔记、链接等)
  • 向PDF添加文本
  • 向PDF添加表格
  • 向PDF添加列表
  • 使用页面布局管理器

9. PyPDF4

  • Github address:PyPDF4

  • 最新发布时间:2018年8月8日

9.1 安装

pip install pypdf

9.2 测试

from pypdf import PdfReaderreader = PdfReader("example.pdf")
page = reader.pages[0]
print(page.extract_text())

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/853204.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

航拍无人机像素坐标转世界坐标

一、背景 已知相机参数&#xff08;传感器宽度和高度、图像宽度和高度、焦距、相对航高、像主点坐标 &#xff09;&#xff0c;在给定像素坐标的前提下&#xff0c;求世界坐标&#xff0c;大部分通过AI来实现&#xff0c;不知道哪个步骤有问题&#xff0c;望大家指正 二、代码…

YOLOv8可视化界面PYQT5

yolov8&#xff0c;可视化界面pyqt。支持图片检测&#xff0c;视频检测&#xff0c;摄像头检测等&#xff0c;实时显示检测画面。支持自定义数据集&#xff0c;计数&#xff0c;fps展示……,即插即用&#xff0c;无需更改太多代码

非关系型数据库NoSQL数据层解决方案 之 Mongodb 简介 下载安装 springboot整合与读写操作

MongoDB 简介 MongoDB是一个开源的面向文档的NoSQL数据库&#xff0c;它采用了分布式文件存储的数据结构&#xff0c;是当前非常流行的数据库之一。 以下是MongoDB的主要特点和优势&#xff1a; 面向文档的存储&#xff1a; MongoDB是一个面向文档的数据库管理系统&#xff0…

TLE9879的基于Arduino调试板SWD刷写接口

官方的Arduino评估板&#xff0c;如下图所示&#xff1a; 如果你有官方的调试器&#xff0c;应该不用关注本文章&#xff0c;如下图连接就是&#xff1a; 如果&#xff0c;您和博主一样需要自己飞线的话&#xff0c;如下图所示&#xff1a;PCB的名称在右边整理&#xff0c;SWD的…

揭秘虾皮电商API:一站式接入,轻松掌握亿万商机

当涉及到虾皮&#xff08;Shopee&#xff09;接口的时&#xff0c;我们需要注意的是虾皮提供了API供开发者使用以集成其平台功能。然而&#xff0c;由于API的具体细节、参数和认证机制可能会随时间变化&#xff0c;以下是一个简化的示例和步骤&#xff0c;用于说明如何与虾皮AP…

Elasticsearch 认证模拟题 - 20

一、题目 定义一个 pipeline&#xff0c;并且将 earthquakes 索引的文档进行更新 pipeline 的 ID 为 earthquakes_pipeline将 magnitude_type 的字段值改为大写如果文档不包含 batch_number&#xff0c;增加这个字段&#xff0c;将数值设置为 1如果已经包含 batch_number&…

大模型系列:Prompt提示工程常用技巧和实践

前言 Prompt提示语是使用大模型解决实际问题的最直接的方式&#xff0c;本篇介绍Prompt提示工程常用的技巧&#xff0c;包括Zero-Shot、Few-Shot、CoT思维链、Least-to-Most任务分解。 内容摘要 Prompt提示工程简述Prompt的一般结构介绍零样本提示Zero-Shot少样本提示Few-Sho…

nginx配置https协议(测试环境)

第一步申请证书 首先申请证书这一步&#xff0c;晚上有很多种方式实现&#xff0c;可以自己用算法实现&#xff0c;也可以找在线生成的网站&#xff0c;我这里使用了在线网站 https://www.toolhelper.cn/SSL/SSLGenerate 第二步将证书放到对应的目录下 这里我们主要用cert.pe…

探索大数据在信用评估中的独特价值

随着我国的信用体系越来越完善&#xff0c;信用将影响越来越多的人。现在新兴的大数据信用和传统信用&#xff0c;形成了互补的优势&#xff0c;大数据信用变得越来越重要&#xff0c;那大数据信用风险检测的重要性主要体现在什么地方呢?本文将详细为大家介绍一下&#xff0c;…

03-appium环境配置和启动参数设置

参考文章&#xff1a;https://blog.csdn.net/lovedingd/article/details/110949993 一、appium介绍 Appium是一个开源、跨平台的自动化测试框架&#xff0c;支持Android、IOS等平台&#xff0c;同时也支持多语言&#xff0c;比如&#xff1a;Java、Python等。 Appiumu通过扩展…

2023-2024山东大学软件学院web数据管理期末

一、填空&#xff08;30*1 30&#xff09; 都是PPT上的&#xff0c;这里列几个复习可能忽略掉的地方&#xff1a; word2vec是用来计算____和___&#xff08;king-manwoman&#xff09; 爬虫模型使用___判重 fastText是一个_____和_____工具&#xff0c;使用_____方法/概念…

图论(一)之概念介绍与图形#matlab

图论&#xff08;一&#xff09;之概念介绍与图形目录 前言 一、图论介绍 二、基本概念 2.1图的概念 2.2图形分类 2.3邻接矩阵 2.3.1无向图 2.3.2有向图 2.3.3有向赋权图 2.4出度&#xff08;Outdegree&#xff09; 2.5入度&#xff08;Indegree&#xff09; 3.四种…

C语言 | Leetcode C语言题解之第145题二叉树的后序遍历

题目&#xff1a; 题解&#xff1a; void addPath(int *vec, int *vecSize, struct TreeNode *node) {int count 0;while (node ! NULL) {count;vec[(*vecSize)] node->val;node node->right;}for (int i (*vecSize) - count, j (*vecSize) - 1; i < j; i, --j)…

web前端人满为患:现状、挑战与未来趋势

web前端人满为患&#xff1a;现状、挑战与未来趋势 在当今数字化时代&#xff0c;Web前端技术已成为互联网行业的热门领域之一。然而&#xff0c;随着技术的普及和市场的扩大&#xff0c;Web前端领域似乎出现了“人满为患”的现象。本文将从四个方面、五个方面、六个方面和七个…

结构体对齐,与 触发 segment fault 为什么是 1024*132 ,而不是1024*128

1, 简单的小示例代码 按理说 malloc 的size 是 1024*128&#xff0c;这里却需要 1024*132才能及时触发 segmentation fault #include <stdlib.h> #include <stdio.h> #define SIZE 1024*131int main() {char *p 0;p malloc(SIZE);p[SIZE -1] a;free(p);printf(…

java学习 项目篇 一

学习地址&#xff1a;https://www.bilibili.com/video/BV1TP411v7v6?p6&spm_id_frompageDriver&vd_sourcea6f7db332f104aff6fadf5b3542e5875 后端环境搭建 Entity 实体&#xff0c;通常和数据库的表对应DTO 数据传输对象&#xff0c;用于程序中各层之间传递数据 (前端…

C++ PDF转图片

C PDF转图片#include "include/fpdfview.h" #include <fstream> #include <include/core/SkImage.h>sk_sp<SkImage> pdfToImg(sk_sp<SkData> pdfData) {sk_sp<SkImage> img;FPDF_InitLibrary(nullptr);FPDF_DOCUMENT doc;FPDF_PAGE …

Android采用Scroller实现底部二楼效果

需求 在移动应用开发中&#xff0c;有时我们希望实现一种特殊的布局效果&#xff0c;即“底部二楼”效果。这个效果类似于在列表底部拖动时出现额外的内容区域&#xff0c;用户可以继续向上拖动查看更多内容。这种效果可以用于展示广告、推荐内容或其他信息。 效果 实现后的…

算法01 递推算法及相关问题详解【C++实现】

目录 递推的概念 训练&#xff1a;斐波那契数列 解析 参考代码 训练&#xff1a;上台阶 参考代码 训练&#xff1a;信封 解析 参考代码 递推的概念 递推是一种处理问题的重要方法。 递推通过对问题的分析&#xff0c;找到问题相邻项之间的关系&#xff08;递推式&a…

【Java】登录模块优化 jwt原理以及使用

上手第一步先整个登录模块&#xff0c;找资料做个优化&#xff0c;感觉找来博客写的很杂乱&#xff0c;原理写的非常冗长&#xff0c;完了用法说的的不清不楚的。自己总结一下&#xff0c;也顺便巩固。 兄弟萌&#xff0c;如果感觉写得好的话&#xff0c;给个赞再叉呗~~ 参考&…