解决pdfplumber解析出来日期出错问题

解决pdfplumber解析出来日期出错问题

使用pdfplumber库解析pdf文档时会出现日期的错乱,即年月日在一行,但具体数字在下一行。错误类型如下:

原文:发行日期位2023年4月5日

pdfplumber库解析出来效果如下:

发行日期位 年 月 日

2023 4 5

解决办法如下,把解析出来的文本传入这个函数中,解析请按行解析,并保留换行符。

python 复制代码
def pdf(text):
    lines = text.split("\n")
    result_text = []
    for i in range(0, len(lines)-1):
        characters1 = [char for char in lines[i]]
        characters2 = lines[i+1].split()

        # 遍历列表中的每个元素
        for item in characters2:
            # 判断元素是否只包含字母和数字
            if not item.isalnum():
                break
        else:
            # 创建一个空列表来存储空格元素的索引
            space_indexes = []
            if characters1[0] == '年':
                characters1.insert(0, ' ')
            # 使用enumerate()函数遍历列表,并获取空格元素的索引
            for index, item in enumerate(characters1):
                if item == ' ':
                    space_indexes.append(index)

            for k, j in zip(space_indexes, characters2):
                characters1[k] = j
            result = ''.join(characters1)
            result_text.append(result)
    wenben = ''.join(result_text)
    return wenben

def paqu(url):
    header={
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"}
    res = requests.get(url=url, headers=header)
    result = res.content
    # 使用pdfplumber提取文字
    if result == b'':
        text = "*"
    else:
        with pdfplumber.open(io.BytesIO(result), strict_metadata=False) as pdf:
            text = ""
            for page in pdf.pages:
                for line in page.extract_text().split('\n'):
                    if line.strip():  # 去除空行
                        text += line + '\n'
    return text
相关推荐
dev派3 分钟前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪2 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户0332126663672 小时前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫3 小时前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派4 小时前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风6 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽15 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805120 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon21 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly21 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent