Извлечение определенных сегментов из документа PDF
У меня есть несколько исследовательских работ в формате PDF, и я хочу извлечь из статьи только введение / справочную информацию и т. Д. Кроме того, я могу использовать только Python. Может кто-нибудь, пожалуйста, помогите?
1 ответ
Я получил помощь прямо здесь, с чем-то похожим пару недель назад. Работать с PDF-файлами может быть легко или ОЧЕНЬ ТРУДНО, и есть все виды PDF-файлов. Сказав это, вы должны рассмотреть возможность преобразования всех файлов PDF в текстовые файлы. Попробуйте пример кода ниже.
Во-первых, конвертировать PDF-файлы в текст.
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/PDF_in/"
txtDir = "C:/your_path_here/TEXT_out/"
convertMultiple(pdfDir, txtDir)
Во-вторых, ищите весь текст между начальным тегом ("Закон о недвижимости штата Нью-Йорк") и конечным тегом ("общие элементы свойства").
# Loop through all TEXT files in a folder
# Pull out all text between two anchors: "New York State Real Property Law" & "common elements of the property."
import re
import os
myRegex=re.compile("New York State Real Property Law.*?common elements of the property\.",re.DOTALL)
for foldername,subfolders,files in os.walk(r"C:/your_path_here/text_files/"):
for file in files:
print(file)
object=open(os.path.join(foldername,file))
Text=object.read()
for subText in myRegex.findall(Text):
print(subText)
object.close()
Возможно, вы можете сделать всю работу без преобразования PDF-файлов в текстовые файлы, но я не нашел способа сделать это.