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是是否存成本地图片文件。

相关推荐
Hello_wshuo6 分钟前
锅炉温控系统优化
linux·python·物联网
weixin_4707403612 分钟前
python生成环境部署
开发语言·python
piaopiaolanghua13 分钟前
Python中的SGP4轨道预报库
python·sgp4
Eiceblue13 分钟前
Python 实现 CSV 转 TXT 格式 (单文件 + 批量处理)
开发语言·python·visual studio code
Iridescent112114 分钟前
Iridescent:Day49
python
曲幽30 分钟前
从安装到上线:一份 Nginx 实战指南,让你的 Web 应用稳建安全
python·nginx·flask·fastapi·web·gunicorn·uvicorn
vibag40 分钟前
LangSmith监控
人工智能·python·语言模型·langchain·大模型
YJlio1 小时前
PsPing 学习笔记(14.7):一条龙网络体检脚本——连通性、延迟、带宽全都要
开发语言·网络·笔记·python·学习·pdf·php
2401_841495641 小时前
【DeepSeek系列】论文《mHC: Manifold-Constrained Hyper-Connections》全流程复现详解(附Python代码)
人工智能·pytorch·python·深度学习·论文复现·deepseek·mhc模型
汤姆yu1 小时前
基于python大数据的地震数据可视化分析系统
大数据·python·信息可视化