PyPDF挂在大图上

时间:2014-10-08 19:41:30

标签: python parsing pypdf

Here is the PDF I'm trying to parse。我的代码(如下)挂在以下行:

 content += " ".join(extract.strip().split())

它挂在第21页,这是一幅大图。我不介意只是跳过像这幅大画的页面,但我不知道该怎么做。有人可以帮帮我吗?

 def ConvertPDFToText(self, pPDF):
    content = ""
    # Load PDF into pyPDF
    remoteFile = urlopen(pPDF).read()
    memoryFile = StringIO(remoteFile)
    pdf = PdfFileReader(memoryFile)
    print("Done reading")
    # Iterate pages
    try:
        numPages = pdf.getNumPages()
        print(str(numPages) + " pages detected")
        for i in range(0, numPages):
            # Extract text from page and add to content
            page = pdf.getPage(i)
            extract = page.extractText() + "\n"
            content += " ".join(extract.strip().split())

    except UnicodeDecodeError as ex:
        print(self._Name + " - Unicode Error extracting pages: " + str(ex))
        return ""
    except Exception as ex:
        print(self._Name + " - Generic Error extracting pages - " + str(ex))
        return ""
    # Decode the content. Since we don't know the encoding, we iterate through some possibilities.

    encodings = ['utf8', 'windows-1250', 'windows-1252', 'utf16', 'utf32']
    DecodedContent = ""
    for code in encodings:
        try:
            DecodedContent = content.decode(code)
            break
        except Exception as ex:
            continue
    return DecodedContent

1 个答案:

答案 0 :(得分:0)

不应使用自2010年以来未更新的pyPdf,而应使用PyPDF2,pyPdf的新分支。你可以在这里得到它:

我刚刚在你的示例PDF上使用它并且它工作正常,尽管解析该文件需要一段时间。这是我使用的代码:

from PyPDF2 import PdfFileReader

#----------------------------------------------------------------------
def parse_pdf(pdf_file):
    """"""
    content = ""
    pdf = PdfFileReader(open(pdf_file, 'rb'))
    numPages = pdf.getNumPages()
    for i in range(0, numPages):
        # Extract text from page and add to content
        page = pdf.getPage(i)
        extract = page.extractText() + "\n"
        content += " ".join(extract.strip().split())

if __name__ == "__main__":
    pdf = "Kicking Horse Mountain Park Construction 2014.pdf"
    parse_pdf(pdf)