import re
import PyPDF2
import importlib
import subprocess
import csv
import os
def install_missing_package(package):
try:
importlib.import_module(package)
except ImportError:
subprocess.check_call(['pip', 'install', package])
def extract_phone_numbers_from_pdf(file_path):
phone_numbers = []
# Open the PDF file
with open(file_path, 'rb') as file:
# Create a PDF reader object
reader = PyPDF2.PdfReader(file)
# Iterate over each page in the PDF
for page in reader.pages:
# Extract the text from the page
text = page.extract_text()
# Use regular expressions to find phone numbers
# This pattern matches US phone numbers in various formats
pattern = r'(\+\d{1,2}\s?)?(\()?(\d{3})(?(2)\))[-.\s]?(\d{3})[-.\s]?(\d{4})'
matches = re.findall(pattern, text)
# Format the phone numbers as (###) ###-####
formatted_numbers = ['({}) {}-{}'.format(*match[2:]) for match in matches]
# Add the matched phone numbers to the list
phone_numbers.extend(formatted_numbers)
return phone_numbers
# Check if PyPDF2 is installed, and install it if necessary
install_missing_package('PyPDF2')
# Read the text file with a list of PDF file names
pdf_list_file = 'pdf_files.txt'
with open(pdf_list_file, 'r') as file:
pdf_files = file.read().splitlines()
# Extract phone numbers from each PDF and store them in a list
phone_number_list = []
for pdf_file in pdf_files:
phone_numbers = extract_phone_numbers_from_pdf(pdf_file)
phone_number_list.extend([(pdf_file, number) for number in phone_numbers])
# Write the extracted phone numbers to a CSV file
csv_file = 'phone_extracts.csv'
with open(csv_file, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['PDF Name', 'Phone Number'])
writer.writerows(phone_number_list)
# Print the success message
print(f"Phone numbers extracted from {len(pdf_files)} PDF files and saved to {csv_file}.")