import PyPDF2
import re
from [Link] import letter
from [Link] import canvas
def extract_circle_questions_from_pdf(pdf_path, output_pdf_path):
# Open the PDF file
with open(pdf_path, 'rb') as file:
reader = [Link](file)
total_pages = len([Link])
# List to hold extracted questions
extracted_questions = []
for page_num in range(total_pages):
page = [Link][page_num]
text = page.extract_text()
# Split the text into lines
lines = [Link]('\n')
question_text = ""
capturing_question = False
for line in lines:
# Check if the line contains "Circle", "circle", "Circles" or
"circles"
# and doesn't match the exclusion conditions
if ("Circle the" not in line and
"Circle your answer" not in line and
[Link](r'\b[Cc]ircle[s]?\b', line)):
capturing_question = True
# If we are capturing a question related to "Circle" or
"Circles", add the line to the question text
if capturing_question:
question_text += line + " "
# If the line ends with a punctuation mark, assume the
question ends here
if [Link](r'[.!?]$', [Link]()):
extracted_questions.append(question_text.strip()) #
Store the question text
question_text = ""
capturing_question = False
# Now, create a new PDF file and write extracted questions into it
create_pdf_with_questions(extracted_questions, output_pdf_path)
def create_pdf_with_questions(questions, output_pdf_path):
# Create a new PDF using reportlab
c = [Link](output_pdf_path, pagesize=letter)
width, height = letter
y_position = height - 40 # Starting y position
# Loop through each extracted question and write it to the new PDF
for question in questions:
if y_position < 40: # If there's no more space on the current page,
start a new page
[Link]()
y_position = height - 40
[Link](40, y_position, question)
y_position -= 20 # Move down for the next question
# Save the new PDF
[Link]()
# Example usage
pdf_file_path = 'C:/Personal/Python/AQA-83002H-QP-NOV18P_OCR.pdf' # Replace
with your actual PDF file path
output_pdf_path = 'C:/Personal/Python/extracted_circle_questions.pdf' # Output
PDF file path
extract_circle_questions_from_pdf(pdf_file_path, output_pdf_path)