phone extract PYTHON code

import re
import PyPDF2
import importlib
import subprocess

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')

# Specify the path to your PDF file
pdf_file_path = 'sample.pdf'

# Extract phone numbers from the PDF file
phone_numbers = extract_phone_numbers_from_pdf(pdf_file_path)

# Print the extracted phone numbers
for number in phone_numbers:
    print(number)

Leave a Reply

Your email address will not be published. Required fields are marked *