信捷PLCSkill
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 

37 wiersze
1.0 KiB

  1. import pathlib
  2. import re
  3. import sys
  4. from pypdf import PdfReader
  5. def compact(text: str) -> str:
  6. return re.sub(r"\s+", " ", text or "").strip()
  7. def main() -> None:
  8. if len(sys.argv) < 3:
  9. raise SystemExit("usage: search_pdf_keywords.py <pdf-path> <keyword> [keyword...]")
  10. pdf_path = pathlib.Path(sys.argv[1])
  11. keywords = sys.argv[2:]
  12. reader = PdfReader(str(pdf_path))
  13. print(f"PDF: {pdf_path}")
  14. print(f"PAGES: {len(reader.pages)}")
  15. for page_index, page in enumerate(reader.pages, start=1):
  16. text = compact(page.extract_text() or "")
  17. if not text:
  18. continue
  19. for keyword in keywords:
  20. if keyword in text:
  21. pos = text.find(keyword)
  22. start = max(0, pos - 160)
  23. end = min(len(text), pos + len(keyword) + 260)
  24. print(f"\nPAGE {page_index} KEYWORD {keyword}")
  25. print(text[start:end])
  26. if __name__ == "__main__":
  27. if hasattr(sys.stdout, "reconfigure"):
  28. sys.stdout.reconfigure(encoding="utf-8")
  29. main()