gpt4 book ai didi

python - 如何在python 2.7中逐行从pdf中提取文本

转载 作者:太空宇宙 更新时间:2023-11-04 10:14:20 24 4
gpt4 key购买 nike

我正在尝试读取和解析包含表格的 PDF 文件...

这是 PDF 中的表格:

Table in pdf

这是我的代码:

import PyPDF2
import re
from PyPDF2 import PdfFileReader , PdfFileWriter
FileRead = open("C:\\Users\\Zahraa Jawad\\S40rooms.pdf", 'rb')
pdfReader = PyPDF2.PdfFileReader(FileRead)
pdfwriter = PdfFileWriter()
for page in pdfReader.pages:
print page.extractText()

我想要的是分别读取表格中的每一行( split )并将所有信息保存在行中( YEAR, SEMESTER, ROOM, DAY, COURSE NO, INSTRUCTOR, TIME FROM, TIME TO, NUMBER OF STUDENTS )中数组。在每个 '\n' 之后,我想将数据保存在数组的新索引中。

但是,我的代码不起作用;它读取所有信息并将其作为段落返回!我不知道如何拆分每一行。

例如(见上面的PDF):

341 458 01 Gazwa Sleebekh UTH 09:00 09:50 30

输出:年、学期、房间、天、类(class)号、讲师、时间从、时间到、学生人数

2015/2016, 第二, S40-021, U, 341, Ghazwa Sleebekh, 09:00, 09:50, 30 2015/2016, 第二, S40-021, T, 341, Ghazwa Sleebekh, 09:00, 09:50, 30 2015/2016, 第二, S40-021, H, 341, Ghazwa Sleebekh, 09:00, 09:50, 30

它被 UTH(Day)拆分,但我的问题是如何读取 PDF 中的每一行并使用正则表达式在其中进行搜索:)

最佳答案

在将 PDF 转换为文本时,我使用来自 popplerpdftotext 获得了最好的结果。实用程序。 (您可以在多个位置找到 ms-windows 二进制文件 [1][2] 。)

import subprocess

def pdftotext(pdf, page=None):
"""Retrieve all text from a PDF file.

Arguments:
pdf Path of the file to read.
page: Number of the page to read. If None, read all the pages.

Returns:
A list of lines of text.
"""
if page is None:
args = ['pdftotext', '-layout', '-q', pdf, '-']
else:
args = ['pdftotext', '-f', str(page), '-l', str(page), '-layout',
'-q', pdf, '-']
try:
txt = subprocess.check_output(args, universal_newlines=True)
lines = txt.splitlines()
except subprocess.CalledProcessError:
lines = []
return lines

请注意,文本提取仅在 PDF 文件实际包含文本时才有效!一些 PDF 文件仅包含文本的扫描图像,在这种情况下,您将需要 OCR 解决方案。

关于python - 如何在python 2.7中逐行从pdf中提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36337463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com