我有一些代码可以从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()
答案 0 :(得分:10)
看起来你所拥有的是一大块想要逐行解释的文本数据。
您可以使用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())
答案 1 :(得分:8)
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
答案 2 :(得分:5)
使用yield
和PdfFileReader.pages
可以简化事情,
from pyPdf import PdfFileReader
def get_pdf_content_lines(pdf_file_path):
with open(pdf_file_path) as f:
pdf_reader = PdfFileReader(f)
for page in pdf_reader.pages:
for line in page.extractText().splitlines():
yield line
for line in get_pdf_content_lines('/path/to/file.pdf'):
print line
此外,有些人可能谷歌" python获取pdf内容文字" 所以这里是如何:(这就是我如何到达这里)
from pyPdf import PdfFileReader
def get_pdf_content(pdf_file_path):
with open(pdf_file_path) as f:
pdf_reader = PdfFileReader(f)
content = "\n".join(page.extractText().strip() for page in pdf_reader.pages)
content = ' '.join(content.split())
return content
print get_pdf_content('/path/to/file.pdf')