views:

26

answers:

0

Here's my code, I'm looking for a way to count the images in the pdfs while I extract the text.

import pyPdf
import os
import csv

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)


PDFWriter = csv.writer(open('/home/nick/TAM_work/text/text.csv', 'a'), delimiter=' ', quotechar='|', quoting=csv.QUOTE_ALL) #assigns PDFWriter and tells it to append the existing file so many PDF's can be entered (in order as well). Also tells it what to take.

def getPDFContent(path):
    content = ""
    # Load PDF into pyPDF
    pdf = pyPdf.PdfFileReader(file(path, "rb"))
    # Iterate pages
    for i in range(0, pdf.getNumPages()):
        # Extract text from page and add to content
        content += pdf.getPage(i).extractText() + "\n"
    # Collapse whitespace
    content = " ".join(content.replace(u"\xa0", " ").strip().split())
    return content

for word in os.listdir("/home/nick/TAM_work/TAM_pdfs"):
    print getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word)
    PDFWriter.writerow ([getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word).encode("ascii", "ignore")])  #applies getPDFContent to all objects in os.listdir and after printing into the terminal renders and saves text in CSV file. .encode... takes out a error that is raised that terminates the program.

I'd love any help, Thanks, Matt