如何让pypdf逐行读取页面内容?

2024-04-16 16:35:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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

或我上面的例子,它给出了“礼品店620百老汇街范布伦,AR 72956”。

如果我可以逐行读取输入,那么我可以很容易地从前两行获得位置名和链表地址,其余的则使用子字符串从第三行获得。

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


Tags: 文件path字符串代码信息streetpdf地址
1条回答
网友
1楼 · 发布于 2024-04-16 16:35:49

您可以尝试使用^{}poppler实用程序调用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

相关问题 更多 >