如何使用 PyPdf 在 pdf 文件中逐行读取? [英] How to read line by line in pdf file using PyPdf?

查看:18
本文介绍了如何使用 PyPdf 在 pdf 文件中逐行读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码可以从 pdf 文件中读取.有没有办法在 Windows 上使用 Pypdf、Python 2.6 从 pdf 文件(不是页面)中逐行读取?

这是阅读pdf页面的代码:

导入pyPdfdef getPDFContent(path):内容 = ""num_pages = 10p = 文件(路径,rb")pdf = pyPdf.PdfFileReader(p)对于范围内的 i (0, num_pages):内容 += pdf.getPage(i).extractText() + "
"content = " ".join(content.replace(u"xa0", " ").strip().split())返回内容

更新:

调用代码是这样的:

f= open('test.txt','w')pdfl = getPDFContent("test.pdf").encode("ascii", "ignore")f. 写(pdfl)f.close()

解决方案

看起来您想要逐行解释一大块文本数据.

您可以使用 StringIO 类将该内容包装为可查找的类文件对象:

<预><代码>>>>导入字符串IO>>>content = 'big ugly contents of multiple pdf 文件'>>>buf = StringIO.StringIO(内容)>>>buf.readline()'大 '>>>buf.readline()'丑 '>>>buf.readline()'内容 '>>>buf.readline()'的 '>>>buf.readline()'多个 '>>>buf.readline()'pdf文件'>>>buf.seek(0)>>>buf.readline()'大 '

在您的情况下,请执行以下操作:

from StringIO import StringIO# 阅读PDF的每一行pdfContent = StringIO(getPDFContent("test.pdf").encode("ascii", "ignore"))对于 pdfContent 中的行:做某事(line.strip())

I have some code to read from a pdf file. Is there a way to read line by line from the pdf file (not pages) using Pypdf, Python 2.6, on Windows?

Here is the code for reading the pdf pages:

import pyPdf

def getPDFContent(path):
    content = ""
    num_pages = 10
    p = file(path, "rb")
    pdf = pyPdf.PdfFileReader(p)
    for i in range(0, num_pages):
        content += pdf.getPage(i).extractText() + "
"
    content = " ".join(content.replace(u"xa0", " ").strip().split())
    return content

Update:

The call code is this:

f= open('test.txt','w')
pdfl = getPDFContent("test.pdf").encode("ascii", "ignore")
f.write(pdfl)
f.close()

解决方案

Looks like what you have is a large chunk of text data that you want to interpret line-by-line.

You can use the StringIO class to wrap that content as a seekable file-like object:

>>> import StringIO
>>> content = 'big
ugly
contents
of
multiple
pdf files'
>>> buf = StringIO.StringIO(content)
>>> buf.readline()
'big
'
>>> buf.readline()
'ugly
'
>>> buf.readline()
'contents
'
>>> buf.readline()
'of
'
>>> buf.readline()
'multiple
'
>>> buf.readline()
'pdf files'
>>> buf.seek(0)
>>> buf.readline()
'big
'

In your case, do:

from StringIO import StringIO

# Read each line of the PDF
pdfContent = StringIO(getPDFContent("test.pdf").encode("ascii", "ignore"))
for line in pdfContent:
    doSomething(line.strip())

这篇关于如何使用 PyPdf 在 pdf 文件中逐行读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆