【问题标题】:How to get pypdf to read page content line by line?如何让pypdf逐行读取页面内容?
【发布时间】:2013-03-17 10:35:50
【问题描述】:

我有一个 pdf,其中每一页都包含一个地址。地址格式如下:

Location Name

Street Address

City, State Zip

例如:

The Gift Store

620 Broadway Street

Van Buren, AR 72956

每个地址都仅采用这种格式,并且每个地址都位于 pdf 的不同页面上。

我需要提取地址信息并将结果存储在 excel/csv 文件中。我需要将每个信息字段的条目分开。我的 Excel 表需要在不同的列中包含位置名称、街道地址、城市、州、邮编。我在 python 中使用 pyPdf。

我已经使用以下代码来执行此操作,但我的代码没有考虑换行符;相反,它将单个页面的整个数据作为连续字符串提供。

import pyPdf  
def getPDFConten(path):
    content = ""
    num_pages = 10
    p = file(path, "rb")
    pdf = pyPdf.PdfFileReader(p)
    for i in range(9, num_pages):
        x = pdf.getPage(i).extractText()+'\n' 
        content += x

    content = " ".join(content.replace(u"\xa0", " ").strip().split())     
    return content

con = getPDFContent("document.pdf")
print con

或者我上面的例子是“The Gift Store 620 Broadway Street Van Buren, AR 72956”。

如果我可以逐行读取输入,那么我可以轻松地从前两行获取位置名称和街道地址,然后使用子字符串从第三行获取其余部分。

我尝试使用 [here(pyPdf ignores newlines in PDF file) 列出的解决方案,但它对我不起作用。我也尝试使用 pdfminer:它可以逐行提取信息,但它首先将 pdf 转换为文本文件,我不想这样做。我只想使用 pyPdf。谁能建议我错在哪里或我错过了什么?这可以使用pyPdf吗?

【问题讨论】:

  • 您能提供一份 PDF 样本吗?如果您引用的解决方案没有帮助,您可能有非常特殊的结构。

标签: python string pdf pypdf


【解决方案1】:

您可以尝试使用subprocesspoppler 实用程序调用pdftotext(可能使用-layout 选项)。它比使用 pypdf 对我来说效果更好。

例如,我使用以下代码从 PDF 文件中提取 CAS 数字:

import subprocess
import re

def findCAS(pdf, page=None):
    '''Find all CAS numbers on the numbered page of a file.

    Arguments:
    pdf -- Name of the PDF file to search
    page -- number of the page to search. if None, search all pages.
    '''
    if page == None:
        args = ['pdftotext', '-layout', '-q', pdf, '-']
    else:
        args = ['pdftotext', '-f', str(page), '-l', str(page), '-layout',
                '-q', pdf, '-']
    txt = subprocess.check_output(args)
    candidates =  re.findall('\d{2,6}-\d{2}-\d{1}', txt)
    checked = [x.lstrip('0') for x in candidates if checkCAS(x)]
    return list(set(checked))

def checkCAS(cas):
    '''Check if a string is a valid CAS number.

    Arguments:
    cas -- string to check
    '''
    nums = cas[::-1].replace('-', '') # all digits in reverse order
    checksum = int(nums[0]) # first digit is the checksum
    som = 0
    # Checksum method from: http://nl.wikipedia.org/wiki/CAS-nummer
    for n, d in enumerate(nums[1:]):
        som += (n+1)*int(d)
    return som % 10 == checksum

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 2022-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多