解决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
相关推荐
用户4019925568612 分钟前
基于对话树回溯的社媒评论流买方意图识别与噪音过滤实践
python
用户03321266636721 分钟前
使用 Python 加密或解密 PDF 文档
python
小七-七牛开发者37 分钟前
让 Go 走得更远:用 LLGo 打通 Go 与 C/C++/Python 生态
python·编程·编译器·llvm·llgo
CyrusYiVPP2 小时前
实测 Ollama 本地部署:我用 Python 搓了个离线问答机器人,Qwen4 27B 一到换个模型名就能用
人工智能·python
2601_967980112 小时前
Python中flatten( )函数及函数用法详解
python·numpy·数组操作·flatten函数·列表处理
xbzb2 小时前
自定义 yum 软件源:Linux 上 createrepo,Windows 上纯 Python 也能造
linux·运维·windows·python·yum·createrepo
合尘猫6 小时前
图片表格变结构化数据:OCR 后的三个坑
python·ocr
小小张说故事6 小时前
Python 里弱引用到底弱在哪:拆开 weakref.ref、回调陷阱和 WeakValueDictionary
python
用户019027581616 小时前
用 DuckDB 存查 A 股 K 线:零服务、SQL 直接分析
python
程序员果子8 小时前
本体构建方法
人工智能·python·知识图谱·agent框架·本体