Update tools/pdfquery
Browse files- tools/pdfquery +44 -27
tools/pdfquery
CHANGED
|
@@ -1,37 +1,54 @@
|
|
| 1 |
-
|
| 2 |
import pypdf
|
| 3 |
|
| 4 |
-
def
|
| 5 |
"""
|
| 6 |
-
Searches for a
|
| 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 |
# Example Usage
|
| 32 |
if __name__ == "__main__":
|
| 33 |
-
# Replace with
|
| 34 |
-
|
| 35 |
-
word_to_find = "
|
| 36 |
|
| 37 |
-
|
|
|
|
| 1 |
+
import os
|
| 2 |
import pypdf
|
| 3 |
|
| 4 |
+
def search_word_in_folder(folder_path, search_word):
|
| 5 |
"""
|
| 6 |
+
Searches for a word across all PDF files in a given folder.
|
| 7 |
"""
|
| 8 |
+
# Normalize the search word for case-insensitive matching
|
| 9 |
+
search_word_lower = search_word.lower()
|
| 10 |
+
|
| 11 |
+
# Check if the folder exists
|
| 12 |
+
if not os.path.exists(folder_path):
|
| 13 |
+
print(f"❌ Error: The folder '{folder_path}' does not exist.")
|
| 14 |
+
return
|
| 15 |
+
|
| 16 |
+
print(f"Scanning folder '{folder_path}' for '{search_word}'...\n")
|
| 17 |
+
overall_matches = 0
|
| 18 |
+
|
| 19 |
+
# Loop through all files in the directory
|
| 20 |
+
for filename in os.listdir(folder_path):
|
| 21 |
+
# Only process files that end with .pdf
|
| 22 |
+
if filename.lower().endswith('.pdf'):
|
| 23 |
+
pdf_path = os.path.join(folder_path, filename)
|
| 24 |
|
| 25 |
+
try:
|
| 26 |
+
with open(pdf_path, 'rb') as file:
|
| 27 |
+
reader = pypdf.PdfReader(file)
|
| 28 |
+
file_has_matches = False
|
| 29 |
+
|
| 30 |
+
# Search page by page
|
| 31 |
+
for page_num, page in enumerate(reader.pages, start=1):
|
| 32 |
+
text = page.extract_text()
|
| 33 |
+
|
| 34 |
+
if text and search_word_lower in text.lower():
|
| 35 |
+
# Print the filename and page number where found
|
| 36 |
+
print(f"✅ Found in [{filename}] on Page {page_num}")
|
| 37 |
+
file_has_matches = True
|
| 38 |
+
overall_matches += 1
|
| 39 |
+
|
| 40 |
+
except Exception as e:
|
| 41 |
+
print(f"⚠️ Could not read file {filename}: {e}")
|
| 42 |
|
| 43 |
+
if overall_matches == 0:
|
| 44 |
+
print("❌ Word not found in any PDF files inside this folder.")
|
| 45 |
+
else:
|
| 46 |
+
print(f"\nSearch complete. Total matches found: {overall_matches}")
|
| 47 |
|
| 48 |
# Example Usage
|
| 49 |
if __name__ == "__main__":
|
| 50 |
+
# Replace with the path to your folder
|
| 51 |
+
my_folder = "./my_pdf_documents"
|
| 52 |
+
word_to_find = "contract"
|
| 53 |
|
| 54 |
+
search_word_in_folder(my_folder, word_to_find)
|