【python】Python将100个PDF文件对应的json文件存储到MySql数据库(源码)【独一无二】

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用系列 2核4GB
简介: 【python】Python将100个PDF文件对应的json文件存储到MySql数据库(源码)【独一无二】


👉博__主👈:米码收割机

👉技__能👈:C++/Python语言

👉公众号👈:测试开发自动化【获取源码+商业合作】

👉荣__誉👈:阿里云博客专家博主、51CTO技术博主

👉专__注👈:专注主流机器人、人工智能等相关领域的开发、测试技术。



1. 需求描述

给100篇PDF文件与其一一对应的json文件,假定这一百篇PDF文件存储于D盘的名为100PDF的文件夹中,json文件存储在D盘名为100JSON的文件夹中。

要求

1.利用python对接数据库,将这100篇PDF和对应的JSON文件存储在名为Mypdf的数据库中。

2.写一段python代码,能够调用这100篇 PDF和其对应的JSON文件。

100_PDF_MetaData.json 部分内容如下:

{
    "elsevier_05cbcb9ef5629bc25e84df43572f9d1eddb9a35f": {
        "date": "1981-12-01T00:00:00",
        "ref_paper": [],
        "conference": "",
        "keywords": [],
        "year": 1981,
        "author": {
            "affiliation": [
                "Chemistry Department, B-017, University of California at San Diego, La Jolla, CA 92093 U.S.A.",
                "Chemistry Department, B-017, University of California at San Diego, La Jolla, CA 92093 U.S.A."
            ],
            "name": [
                "R.W. Carlson",
                "G.W. Lugmair"
            ]
        },
        "last_page": 8,
        "link": "https://www.sciencedirect.com/science/article/abs/pii/0012821X81901126",
        "abstract": "Pristine samples from the lunar highlands potentially offer important information bearing on the nature of early crustal development on all the terrestrial planets. One apparently unique sample of this group of lunar crustal rocks, the feldspathic lherzolite 67667, was studied utilizing the Sm-Nd radiometric system in an attempt to define its age and the implications of that age for the evolution of the lunar highlands. Data for 67667 precisely define an isochron corresponding to an age of 4.18\u00b10.07 AE. The observed lack of disturbance of the Sm-Nd system of this sample may suggest that this time marks its crystallization at shallow depth in the lunar crust. However, the possibility that this age, as well as those of other highland rocks, indicate the time of their impact-induced excavation from regions deep enough in the lunar crust to allow subsolidus isotopic equilibrium to be produced or maintained between their constituent minerals is also considered. Taken together, bulk rock Sm-Nd data for four \u201chigh-Mg\u201d rocks, including 67667, indicate that the chemical characteristics of all their source materials were established 4.33\u00b10.08 AE ago and were intimately associated with the parent materials of KREEP. This finding provides more support for the concept of a large-scale differentiation episode early in lunar history. The possible roles of the crystallization of a global magma ocean, endogenous igneous activity, and of planetesimal impact, in producing the observed geochemical and chronological aspects of lunar highland rocks are discussed.",
        "title": "Sm-Nd age of lherzolite 67667: implications for the processes involved in lunar crustal formation",
        "paper_id": "elsevier_05cbcb9ef5629bc25e84df43572f9d1eddb9a35f",
        "volume": 56,
        "update_time": "2022-07-16T14:06:08.117141",
        "journal": "Earth and Planetary Science Letters",
        "issn": "0012-821X",
        "first_page": 1,
        "publisher": "elsevier",
        "doi": "10.1016/0012-821X(81)90112-6"
    },
    ....略...
 }

pdf文档内容如下:


2. 结果展示

json数据表:

关注公众号,回复 “PDF数据库存储” 获取源码👇👇👇

论文内容数据表:

关注公众号,回复 “PDF数据库存储” 获取源码👇👇👇


3. 代码分析

当然,让我们更详细地分析这段代码的每个部分:

3. 1 导入模块

  • os:用于文件和目录操作,如遍历目录和打开文件。
  • pymysql:一个Python库,用于连接和操作MySQL数据库。
  • PyPDF2:Python库,用于读取PDF文件。
  • json:内置库,用于处理JSON数据,这里主要用于读取JSON文件。

3.2 数据库配置

  • db_config:一个字典,包含连接MySQL数据库所需的信息(如主机、用户、密码、数据库名)。

3.3 数据库连接

  • 使用pymysql.connect建立到MySQL的连接。
  • cursor对象用于执行SQL命令。

3.4 创建数据库表

  • CREATE TABLE SQL语句被用来创建两个表:paper_metadata(存储论文的元数据)和paper_content(存储论文的PDF内容)。
  • IF NOT EXISTS确保如果表已存在,不会重复创建。

3.5 数据插入函数

  • insert_metadata:将JSON中的元数据插入paper_metadata表。这里处理了如作者、出版日期等多种字段。
  • insert_content:将PDF文件的内容插入paper_content表。这里只提取了PDF的第一页内容。
  • 使用cursor.execute来执行SQL插入命令,并且在每次插入后调用connection.commit来提交事务。

3.6 加载和处理JSON数据

  • 从指定路径加载JSON文件,其中包含与PDF文件相关联的元数据。
  • 遍历一个特定目录中的PDF文件,使用PyPDF2读取每个文件,提取第一页内容。
  • 对于每个PDF,如果它的ID在JSON元数据中,它的内容和元数据将被插入到数据库中。

3.7数据检索函数

  • retrieve_data:根据paper_idpaper_metadatapaper_content表中检索信息。
  • 使用cursor.execute执行查询,并通过cursor.fetchone获取结果。

1.8 示例检索和清理

  • 使用retrieve_data函数来检索特定paper_id的数据。
  • 如果找到数据,它将被打印出来;如果没有,会打印一条消息表示没有找到数据。
  • 最后,代码清理部分关闭了数据库游标和连接。

部分代码

部分代码如下:

import os
import pymysql
from PyPDF2 import PdfReader
import json
# 数据库配置
db_config = {
    'host': '127.0.0.1',
    'user': 'root',
    'password': 'root',
    'database': 'Mypdf'
}
# 连接数据库
connection = pymysql.connect(**db_config)
cursor = connection.cursor()
# 创建表格 - paper_metadata
cursor.execute("""
    CREATE TABLE IF NOT EXISTS paper_metadata (
        paper_id VARCHAR(255) PRIMARY KEY,
        # ...略....
    )
""")
# 创建表格 - paper_content
cursor.execute("""
      ...略
      (源码关注公众号:测试开发自动化, 
       回复 “PDF数据库存储” 获取)
""")
# 插入数据的函数 - paper_metadata
def insert_metadata(paper_id, json_data):
    query = """
        INSERT INTO paper_metadata (paper_id, title, date, year, abstract, authors, affiliations, last_page, first_page, link, ref_paper, conference, keywords, volume, update_time, journal, issn, publisher, doi)
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
    """
    authors = ', '.join(json_data['author']['name'])
    affiliations = ', '.join(json_data['author']['affiliation'])
    cursor.execute(query, (paper_id, json_data['title'], json_data['date'], json_data['year'], json_data['abstract'], authors, affiliations, json_data['last_page'], json_data['first_page'], json_data['link'], str(json_data['ref_paper']), json_data['conference'], str(json_data['keywords']), json_data['volume'], json_data['update_time'], json_data['journal'], json_data['issn'], json_data['publisher'], json_data['doi']))
    connection.commit()
 ...略
# 检索数据的函数
def retrieve_data(paper_id):
    # 查询metadata表
    query_metadata = "SELECT * FROM paper_metadata WHERE paper_id = %s"
  # ...略
  
    # 查询content表
    query_content = "SELECT pdf_content FROM paper_content WHERE paper_id = %s"
    # ...略
# 检索数据的示例
result = retrieve_data("elsevier_05cbcb9ef5629bc25e84df43572f9d1eddb9a35f")
if result:
    print(result)
else:
    print("No data found for this paper ID.")
# 关闭连接
cursor.close()
connection.close()

关注公众号,回复 “PDF数据库存储” 获取源码👇👇👇


相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
4天前
|
Java Apache Maven
将word文档转换成pdf文件方法
在Java中,将Word文档转换为PDF文件可采用多种方法:1) 使用Apache POI和iText库,适合处理基本转换需求;2) Aspose.Words for Java,提供更高级的功能和性能;3) 利用LibreOffice命令行工具,适用于需要开源解决方案的场景。每种方法都有其适用范围,可根据具体需求选择。
|
4天前
|
Java Apache Maven
Java将word文档转换成pdf文件的方法?
【10月更文挑战第13天】Java将word文档转换成pdf文件的方法?
12 1
|
6天前
|
存储 关系型数据库 MySQL
PACS系统 中 dicom 文件在mysql 8.0 数据库中的 存储和读取(pydicom 库使用)
PACS系统 中 dicom 文件在mysql 8.0 数据库中的 存储和读取(pydicom 库使用)
13 2
|
9天前
|
JSON 数据格式 Python
Python实用记录(十四):python统计某个单词在TXT/JSON文件中出现的次数
这篇文章介绍了一个Python脚本,用于统计TXT或JSON文件中特定单词的出现次数。它包含两个函数,分别处理文本和JSON文件,并通过命令行参数接收文件路径、目标单词和文件格式。文章还提供了代码逻辑的解释和示例用法。
22 0
Python实用记录(十四):python统计某个单词在TXT/JSON文件中出现的次数
|
14天前
|
SQL 存储 关系型数据库
SQL文件导入MySQL数据库的详细指南
数据库中的数据转移是一项常规任务,无论是在数据迁移过程中,还是在数据备份、还原场景中,导入导出SQL文件显得尤为重要。特别是在使用MySQL数据库时,如何将SQL文件导入数据库是一项基本技能。本文将详细介绍如何将SQL文件导入MySQL数据库,并提供一个清晰、完整的步骤指南。这篇文章的内容字数大约在
31 1
|
14天前
|
计算机视觉 Python
Python操作PDF文件
Python操作PDF文件
19 1
|
5天前
|
JavaScript 前端开发 容器
Vue生成PDF文件攻略:html2canvas与jspdf联手,中文乱码与自动换行难题攻克
Vue生成PDF文件攻略:html2canvas与jspdf联手,中文乱码与自动换行难题攻克
11 0
|
10天前
|
Oracle 关系型数据库 数据库
oracle数据恢复—Oracle数据库文件损坏导致数据库打不开的数据恢复案例
打开oracle数据库时报错,报错信息:“system01.dbf需要更多的恢复来保持一致性,数据库无法打开”。急需恢复zxfg用户下的数据。 出现上述报错的原因有:控制文件损坏、数据文件损坏、数据文件与控制文件的SCN不一致等。数据恢复工程师对数据库文件做进一步检测分析后发现sysaux01.dbf文件有坏块。修复sysaux01.dbf文件,启动数据库依然有许多查询报错。export和data pump工具无法使用,查询告警日志并分析报错,确认发生上述错误的原因就是sysaux01.dbf文件损坏。由于该文件损坏,从数据库层面无法修复数据库。由于system和用户表空间的数据文件是正常的,
|
17天前
|
JSON 数据格式 Python
Python编程:利用JSON模块编程验证用户
Python编程:利用JSON模块编程验证用户
16 1
|
18天前
|
存储 JSON 数据格式
Python 输入输出与文件处理: io、pickle、json、csv、os.path 模块详解
Python 输入输出与文件处理: io、pickle、json、csv、os.path 模块详解
25 0

热门文章

最新文章