Python读取PDF文档中的表格数据

2022/9/6 14:34:11

本文主要是介绍Python读取PDF文档中的表格数据,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

# -*- coding: utf-8 -*-
# 在pdfplumber模块中 提供了extract_tables()方法
import pdfplumber
import pandas as pd


# 提取PDF文档中的表格
def demo1():
    with pdfplumber.open('file/7_2.pdf') as pdf:
        page = pdf.pages[1]
        for table in page.extract_tables():
            print(table)
        pdf.close()


# 批量提取PDF文档中的表格并写入Excel
def demo2():
    a = 0
    with pdfplumber.open('file/历年中国电影票房榜.pdf') as pdf:
        for i in range(len(pdf.pages)):
            page = pdf.pages[1]
            for table in page.extract_tables():
                df = pd.DataFrame(table)
                df.to_excel(f'file/new_file/{a+2012}年中国电影票房榜单.xlsx', index=None, header=None)
                a += 1
                print(table)
            pdf.close()


demo1()
demo2()


demo1()运行结果

[['排名', '上映日期', '影片名称', '总票房(亿)'], ['1', '2021/9/30', '长津湖', '57.7'], ['2', '2021/2/12', '你好,李焕英', '54.1'], ['3', '2021/2/12', '唐人街探案3', '45.2'], ['4', '2021/9/30', '我和我的父辈', '14.8'], ['5', '2021/5/21', '速度与激情9', '13.9'], ['6', '2021/7/30', '怒火·重案', '13.3'], ['7', '2021/7/9', '中国医生', '13.3'], ['8', '2021/3/26', '哥斯拉大战金刚', '12.3'], ['9', '2020/12/31', '送你一朵小红花', '12.0'], ['10', '2021/4/30', '悬崖之上', '11.9'], ['11', '2021/2/12', '刺杀小说家', '10.4'], ['12', '2021/11/11', '扬名立万', '9.2'], ['13', '2021/4/2', '我的姐姐', '8.6'], ['14', '2021/12/17', '误杀2', '8.4'], ['15', '2021/4/30', '你的婚礼', '7.9'], ['16', '2021/2/12', '人潮汹涌', '7.6'], ['17', '2020/12/24', '拆弹专家2', '7.1'], ['18', '2020/12/31', '温暖的抱抱', '6.7'], ['19', '2021/8/27', '失控玩家', '6.1'], ['20', '2021/7/23', '白蛇2:青蛇劫起', '5.8']]

demo2()运行结果

 


 

 

 



这篇关于Python读取PDF文档中的表格数据的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程