当前位置: 首页 > news >正文

Python 读取电子发票PDF 转成Excel

Python 读取电子发票PDF 转成Excel

目录

0.前提

1.python相关的处理PDF的库

2.实际好用的

3.实际代码        

4.思考


0.前提

        只识别普通电子发票PDF,提取其中某些关键内容到excel中。

1.python相关的处理PDF的库

        如下4个库是经常更新维护的!

        pyPDF/pyPDF2、pdfplumber、PyMuPDF、Camelot等4个库。

2.实际好用的

        个人推荐pdfplumber,它有extract_tables函数

3.实际代码        

import pdfplumber
import re
import os
import pandas as pd
'''处理 普通发票电子PDF 提取关键字段内容信息写入excel中其它类的发票 自己参考对应规律  更改代码即可参考:pdfplumber官网、以及:https://blog.csdn.net/Burannnn/article/details/129393295
'''
def re_text(bt, text):# re 搜索正则匹配 包含re.compile包含的文字内容m1 = re.search(bt, text)if m1 is not None:return re_block(m1[0])return Nonedef re_block(text):# 去掉空格、中英文小括号、中文冒号变英文冒号;去掉中文全角空格return text.replace(' ', '').replace(' ', '').replace(')', '').replace(')', '').replace(':', ':')def get_pdf(dir_path):pdf_file = []for root, sub_dirs, file_names in os.walk(dir_path):for name in file_names:if name.endswith('.pdf'):filepath = os.path.join(root, name)pdf_file.append(filepath)return pdf_filedef read(xlsx_path, pdf_root):# 构建excel writer 写入器writer = pd.ExcelWriter(xlsx_path)# 如果字段不通用 则需要单独拎出来判断,这里我全部拎出来做了if判断all_fields = {"开票日期": [],"名称": [],"纳税人识别号": [],"价税合计(小写)": [],"货物或应税劳务、服务名称": [],"规格型号": [],"单位": [],"数量": [],"单价": [],"金额": [],"税率": [],"税额": [],}filenames = get_pdf(pdf_root)for filename in filenames:print(f"正在读取:{filename}")with pdfplumber.open(filename) as pdf:first_page = pdf.pages[0]pdf_text = first_page.extract_text()# print(pdf_text)kaipiao = re_text(re.compile(r'开票日期(.*)'), pdf_text)if kaipiao:all_fields["开票日期"].append(kaipiao.replace("开票日期:", ""))mingcheng = re_text(re.compile(r'名\s*称\s*[::]\s*([\u4e00-\u9fa5]+)'), pdf_text)if mingcheng:all_fields["名称"].append(mingcheng.replace("名称:", ""))# nashuiren = re_text(re.compile(r'纳税人识别号\s*[::]\s*([a-zA-Z0-9]+)'), pdf_text)# if nashuiren:#     all_fields["纳税人识别号"].append(nashuiren.replace("纳税人识别号:", ""))jine = re_text(re.compile(r'小写.*(.*[0-9.]+)'), pdf_text)if jine:all_fields["价税合计(小写)"].append(jine.replace("小写¥", ""))table = first_page.extract_tables()[0]# 纳税人识别号 购买方for t in table[0]:t_ = str(t).replace(" ", "")nashuiren = re_text(re.compile(r'纳税人识别号\s*[::]\s*([a-zA-Z0-9]+)'), t_)if nashuiren:all_fields["纳税人识别号"].append(nashuiren.replace("纳税人识别号:", ""))# 这里根据pdfplumber提取table来依次输出,查看规律(适合普通发票,其它发票打印输出看规律即可)for t in table[1]:if not t:continuet_ = str(t).replace(" ", "") # 去掉空格ts = t_.split("\n")if "货物或应税劳务、服务名称" in t_:if len(ts) > 1:all_fields["货物或应税劳务、服务名称"].append(ts[1])else:all_fields["货物或应税劳务、服务名称"].append("")if "规格型号" in t_:if len(ts) > 1:all_fields["规格型号"].append(ts[1])else:all_fields["规格型号"].append("")if "单位" in t_:if len(ts) > 1:all_fields["单位"].append(ts[1])else:all_fields["单位"].append("")if "数量" in t_:if len(ts) > 1:all_fields["数量"].append(ts[1])else:all_fields["数量"].append("")if "单价" in t_:if len(ts) > 1:all_fields["单价"].append(ts[1])else:all_fields["单价"].append("")if "税率" in t_:if len(ts) > 1:all_fields["税率"].append(ts[1])else:all_fields["税率"].append("")if "金额" in t_:if len(ts) > 1:all_fields["金额"].append(ts[1])else:all_fields["金额"].append("")if "税额" in t_:if len(ts) > 1:all_fields["税额"].append(ts[1])else:all_fields["税额"].append("")# print('--------------------------------------------------------')# print(re_text(re.compile(r'[\u4e00-\u9fa5]+电子普通发票.*?'), pdf_text))# # print(re_text(re.compile(r'发票代码(.*\d+)'), pdf_text))# print(re_text(re.compile(r'发票号码(.*\d+)'), pdf_text))# print(re_text(re.compile(r'开票日期(.*)'), pdf_text))# print(re_text(re.compile(r'名\s*称\s*[::]\s*([\u4e00-\u9fa5]+)'), pdf_text))# print(re_text(re.compile(r'纳税人识别号\s*[::]\s*([a-zA-Z0-9]+)'), pdf_text))# price = re_text(re.compile(r'小写.*(.*[0-9.]+)'), pdf_text)# print(price)# company = re.findall(re.compile(r'名.*称\s*[::]\s*([\u4e00-\u9fa5]+)'), pdf_text)# if company:#     print(re_block(company[len(company)-1]))# print('--------------------------------------------------------')print(all_fields)df = pd.DataFrame(all_fields)df.to_excel(writer)writer.save()returnpdf_root = r"G:\PDF"
xlsx_path = r"G:\PDF\all_fields.xlsx"read(xlsx_path, pdf_root)

4.思考

        对于专用发票,找到对应的规律即可。这里最好用的是extract_tables函数,打印出来,找规律即可!

http://www.lryc.cn/news/254601.html

相关文章:

  • 我的项目问题
  • 【c】杨辉三角
  • 算法刷题之数组篇
  • TR转发路由器测评—云企业网实现跨地域跨VPC的网络互通测评实战【阿里云产品测评】
  • 1.1美术理论基础
  • 【Java 基础】21 多线程同步与锁
  • Python语言基础知识(一)
  • Xilinx FPGA平台DDR3设计详解(三):DDR3 介绍
  • 字典的遍历
  • Linux环境下的MySQL安装
  • 梦想与魔法:编程之路的挑战与荣耀
  • qt 5.15.2 主窗体菜单工具栏树控件功能
  • Day15——File类与IO流
  • 【Qt】QLineEdit显示输入十六进制,位数不足时按照规则填充显示及每两个字符以空格填充
  • GPT 中文提示词技巧:参照 OpenAI 官方教程
  • 原生微信小程序将字符串生成二维码图片
  • 深入理解HTTPS加密协议
  • 路径规划之PRM算法
  • 深入理解数据在内存中是如何存储的,位移操作符如何使用(能看懂文字就能明白系列)文章超长,慢慢品尝
  • ArcGIS提示当前许可不支持影像服务器
  • Android P 9.0 增加以太网静态IP功能
  • Android12之MediaCodec硬编解码调试手段(四十九)
  • 2.Ansible的copy模块,我最常用的模块
  • python程序将部分文件复制到指定目录
  • 5分钟教你利用服务器,打造1个 7*24H直播的直播间
  • 卡通渲染总结《二》
  • 严蔚敏数据结构p17(2.19)——p18(2.24) (c语言代码实现)
  • 0007Java程序设计-ssm基于微信小程序的在线考试系统
  • php 使用多线程
  • 基于MapBox的方法封装及调用