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

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

问题描述

我有一些要从pdf文件读取的代码.是否可以在Windows上使用Pypdf,Python 2.6从pdf文件(不是页面)逐行读取内容?

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?

以下是阅读pdf页面的代码:

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() + "\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()

推荐答案

您所拥有的似乎是一大堆要逐行解释的文本数据.

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

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

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

>>> 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'

根据您的情况,执行以下操作:

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天全站免登陆