Python PDF文件转文本

该代码示例展示了如何利用Python的PyPDF2库从PDF文件中提取文本,统计单词数量和页面数,并将结果保存为JSON文件。它遍历PDF的每一页,合并文本,并计算词数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

比较简单的实现,代码用到了PyPDF2,函数返回一个json结构

import PyPDF2
import json

def convert_pdf_to_text(pdf_file, text_file):
    # Open the PDF file in binary mode
    with open(pdf_file, 'rb') as file:
        pdf_reader = PyPDF2.PdfReader(file)

        # Get the total number of pages in the PDF
        pages = pdf_reader.pages

        # Initialize counters
        word_count = 0
        graph_count = 0

        # Extract text from each page and count words and graphs
        text = ''
        for page in pages:
            #page = pdf_reader.getPage(page_number)
            text += page.extract_text()
            # Count words
            word_count += len(text.split())

    # Save the text to a text file
    with open(text_file, 'w', encoding='utf-8') as file:
        file.write(text)

    # Create a dictionary with the counts
    counts = {
        'word_count': word_count,
        'page_count': len(pages)
    }

    # Save the counts to a JSON file
    json_file = text_file.replace('.txt', '.json')
    with open(json_file, 'w') as file:
        json.dump(counts, file)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原子星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值