File size: 2,042 Bytes
37f7e27
adb0cac
 
37f7e27
adb0cac
37f7e27
adb0cac
37f7e27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adb0cac
37f7e27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adb0cac
37f7e27
 
 
 
adb0cac
 
 
37f7e27
 
 
adb0cac
37f7e27
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import os
import pypdf

def search_word_in_folder(folder_path, search_word):
    """
    Searches for a word across all PDF files in a given folder.
    """
    # Normalize the search word for case-insensitive matching
    search_word_lower = search_word.lower()
    
    # Check if the folder exists
    if not os.path.exists(folder_path):
        print(f"❌ Error: The folder '{folder_path}' does not exist.")
        return

    print(f"Scanning folder '{folder_path}' for '{search_word}'...\n")
    overall_matches = 0

    # Loop through all files in the directory
    for filename in os.listdir(folder_path):
        # Only process files that end with .pdf
        if filename.lower().endswith('.pdf'):
            pdf_path = os.path.join(folder_path, filename)
            
            try:
                with open(pdf_path, 'rb') as file:
                    reader = pypdf.PdfReader(file)
                    file_has_matches = False
                    
                    # Search page by page
                    for page_num, page in enumerate(reader.pages, start=1):
                        text = page.extract_text()
                        
                        if text and search_word_lower in text.lower():
                            # Print the filename and page number where found
                            print(f"✅ Found in [{filename}] on Page {page_num}")
                            file_has_matches = True
                            overall_matches += 1
                            
            except Exception as e:
                print(f"⚠️ Could not read file {filename}: {e}")
                
    if overall_matches == 0:
        print("❌ Word not found in any PDF files inside this folder.")
    else:
        print(f"\nSearch complete. Total matches found: {overall_matches}")

# Example Usage
if __name__ == "__main__":
    # Replace with the path to your folder
    my_folder = "./my_pdf_documents" 
    word_to_find = "contract"
    
    search_word_in_folder(my_folder, word_to_find)