Кроме того, нельзя использовать перегруженные конструкторы. Это должно быть сделано одним конструктором.
blockquote>Единственная причина, по которой я могу думать об этом требовании, состоит в том, что необязательные аргументы имеют один и тот же тип. В этом случае вы застряли, и вам захочется заглянуть в named constructor и / или с именем id .
В противном случае просто определите дополнительный конструктор. Это может привести к некоторому дублированию. значения по умолчанию.
Foo(int arg1 , char const *arg2 = "arg2", int arg3 = 1) { construct(arg1, arg2, arg3); } Foo(int arg1, int arg3) { construct(arg1, "arg2", arg3); }
Вот как бы я это сделал.
from io import StringIO
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
import os
import sys, getopt
#converts pdf, returns its text content as a string
def convert(fname, pages=None):
if not pages:
pagenums = set()
else:
pagenums = set(pages)
output = io.StringIO()
manager = PDFResourceManager()
converter = TextConverter(manager, output, laparams=LAParams())
interpreter = PDFPageInterpreter(manager, converter)
infile = open(fname, 'rb')
for page in PDFPage.get_pages(infile, pagenums):
interpreter.process_page(page)
infile.close()
converter.close()
text = output.getvalue()
output.close
return text
#converts all pdfs in directory pdfDir, saves all resulting txt files to txtdir
def convertMultiple(pdfDir, txtDir):
if pdfDir == "": pdfDir = os.getcwd() + "\\" #if no pdfDir passed in
for pdf in os.listdir(pdfDir): #iterate through pdfs in pdf directory
fileExtension = pdf.split(".")[-1]
if fileExtension == "pdf":
pdfFilename = pdfDir + pdf
text = convert(pdfFilename) #get string of text content of pdf
textFilename = txtDir + pdf + ".txt"
textFile = open(textFilename, "w") #make text file
textFile.write(text) #write text to text file
# set paths accordingly:
pdfDir = "C:/your_path_here/"
txtDir = "C://your_path_here/"
convertMultiple(pdfDir, txtDir)
Этот ответ использует код ('utf-8') , чтобы сохранить вывод на страницу вместе. Я не знаю, какой вывод вам нужен, потому что он не был указан в вашем вопросе.
from PyPDF2 import PdfFileReader
def pdf_text_extractor(path):
with open(path, 'rb') as f:
pdf = PdfFileReader(f)
# Get total pdf page number.
totalPageNumber = pdf.numPages
currentPageNumber = 0
while (currentPageNumber < totalPageNumber):
page = pdf.getPage(currentPageNumber)
text = page.extractText()
# The encoding put each page on a single line.
# type is <class 'bytes'>
print(text.encode('utf-8'))
#################################
# This outputs the text to a list,
# but it doesn't keep paragraphs
# together
#################################
# output = text.encode('utf-8')
# split = str(output, 'utf-8').split('\n')
# print (split)
#################################
# Process next page.
currentPageNumber += 1
path = 'mypdf.pdf'
pdf_text_extractor(path)
Документация для PyPDF2 и функции extractText () гласит:
extractText()
Locate all text drawing commands, in the order they are provided in the
content stream, and extract the text. This works well for some PDF files, but
poorly for others, depending on the generator used. This will be refined in
the future. Do not rely on the order of text coming out of this function, as
it will change if this function is made more sophisticated.
Returns: a unicode string object.
Это означает, что извлечение текста точно так же, как форматированный текст PDF может быть проблематичным.
Вы можете использовать тика для выполнения этой задачи, но опять же она не будет полностью чистой.
from tika import parser
parse_entire_pdf = parser.from_file('mypdf.pdf', xmlContent=True)
parse_entire_pdf = parse_entire_pdf['content']
print (parse_entire_pdf)
Реальный вопрос - как вы планируете использовать извлеченный текст?