怎样用python读取pdf文件?并把它转换为word或TXT文件?

发布于:2024-03-29 ⋅ 阅读:(21) ⋅ 点赞:(0)

要使用Python读取PDF文件,可以使用第三方库PyPDF2。首先,确保已经安装了PyPDF2库。可以通过运行以下命令来安装:

pip install PyPDF2

以下是一个示例代码,展示如何使用PyPDF2库读取PDF文件并将其转换为TXT文件:

import PyPDF2

def convert_pdf_to_txt(file_path):
    with open(file_path, 'rb') as file:
        pdf_reader = PyPDF2.PdfReader(file)
        text = ''
        for page in pdf_reader.pages:
            text += page.extract_text()
    return text

file_path = 'example.pdf'
text = convert_pdf_to_txt(file_path)

with open('output.txt', 'w', encoding='utf-8') as file:
    file.write(text)

上述代码中,首先使用PyPDF2.PdfReader()打开要读取的PDF文件。然后,使用extract_text()方法提取每一页的文本,并将其添加到最终的文本字符串text中。

然后,使用open()函数将文本字符串写入到TXT文件。

要将PDF文件转换为Word文件,可以使用第三方库python-docx。安装python-docx库:

pip install python-docx
然后,可以使用以下示例代码将PDF文件转换为Word文档:import PyPDF2
from docx import Document

def convert_pdf_to_docx(file_path):
    document = Document()
    with open(file_path, 'rb') as file:
        pdf_reader = PyPDF2.PdfReader(file)
        for page in pdf_reader.pages:
            text = page.extract_text()
            document.add_paragraph(text)
    return document

file_path = 'example.pdf'
document = convert_pdf_to_docx(file_path)

document.save('output.docx')

上述代码中,首先创建一个Document对象,然后使用PyPDF2.PdfReader()打开PDF文件。接下来,使用extract_text()方法提取每一页的文本,并使用add_paragraph()方法将文本添加到Word文档中。

最后,使用save()方法将Word文档保存为DOCX文件。

使用Python将PDF转换为TXT或Word文档时,转换结果可能会因PDF文件的格式和布局而异。某些复杂的PDF文件可能无法完全准确地转换为文本或Word文档。

本文含有隐藏内容,请 开通VIP 后查看