问题:如何使用PyPdf逐行读取pdf文件?

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

这是阅读pdf页面的代码:

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() + "\n"
    content = " ".join(content.replace(u"\xa0", " ").strip().split())
    return content

更新:

调用代码是这样的:

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

解答

看起来您拥有的是要逐行解释的大量文本数据。

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

>>> import StringIO
>>> content = 'big\nugly\ncontents\nof\nmultiple\npdf files'
>>> buf = StringIO.StringIO(content)
>>> buf.readline()
'big\n'
>>> buf.readline()
'ugly\n'
>>> buf.readline()
'contents\n'
>>> buf.readline()
'of\n'
>>> buf.readline()
'multiple\n'
>>> buf.readline()
'pdf files'
>>> buf.seek(0)
>>> buf.readline()
'big\n'

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

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())
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐