pdf读取函数,可以读取本地pdf和url的在线pdf转换为文字

python 复制代码
import requests
from lxml import etree
import os
import urllib
from PIL import Image
from pymysql.converters import escape_string
import sys
import time
from selenium import webdriver
import warnings
import pdfplumber
from urllib import request
import io
import socks
import urllib.parse
import pymysql
import socks
import configparser
import hashlib
import threading
import urllib.parse
import re


def read_pdf(path,proxies={},timeout=(3.2,10),download_image=False):
    f=''
    if path=='' or type(path)!=str:
        print("路径为空或格式不对!")
    if path[0:4]=="http":
        try:
            #data=request.urlopen(path,timeout=10).read()
            print(proxies)
            data=requests.get(url=path,timeout=timeout,proxies=proxies)
            f = io.BytesIO(data.content)
        except Exception as e:
            print(e,"打开链接失败")
            return ''
    else:
        try:
            path=urllib.parse.unquote(path)
            path=path.replace('file:///','').replace('/','\\')
            f=open(path,'rb')
        except Exception as e:
            print(e,"打开本地文件失败")

    text=''
    old_path=os.getcwd()
    if download_image:
        im_path=path.replace('https://','').replace("http://",'')
        os.makedirs(im_path, exist_ok=True)
        os.chdir(im_path)
    
    with pdfplumber.open(f) as pdf:
    # 遍历每个页面
        for page in pdf.pages:
            # 获取当前页面的全部文本信息,包括表格中的文字,没有内容则打印None
            text+=page.extract_text()
            if download_image:
                images=page.images
                i=0
                for img in images:
                    f_img=open('{}.png'.format(i),'wb+')
                    f_img.write(img['stream'].get_data())
                    f_img.close()
                    i+=1
    os.chdir(old_path)
    f.close()
    return text

可用库自己筛选一下,我把全部的加进来了,proxies是http代理,path是路径,download_image是是否存成本地图片文件。

相关推荐
蓝创工坊Blue Foundry13 小时前
扫描件批量转 Excel:先确认要整表还原还是字段汇总
python·pdf·ocr·excel
二十雨辰13 小时前
[爬虫]-解析
开发语言·python
天天爱吃肉821814 小时前
AI Agent时代你的经验值多少钱?
人工智能·python·功能测试·学习·汽车
鱼香鱼香rose14 小时前
java-2
java·开发语言·python
tkevinjd1 天前
MiniCode 项目详解6:原项目控制系统的10个缺陷(已修复)
python·llm·agent
dNGUZ7UGj1 天前
10分钟完成第一个Python小游戏
python·django
没有梦想的咸鱼185-1037-16631 天前
AI-Python机器学习与深度学习技术:CNN/Transformer/扩散模型、SHAP可解释及Hermes智能体自动化
人工智能·python·深度学习·机器学习·chatgpt·cnn·transformer
霸道流氓气质1 天前
SpringBoot中通用工具类库(Utils)封装与使用实践
spring boot·后端·python
Draina1 天前
CBC填充预言攻击-CBC Padding Oracle Crypto Attack
python·安全·web安全·网络安全·密码学·安全性测试
Angel Q.1 天前
特征提取 | DINO 到 DINOv3
图像处理·python