Python script to get the count of words in a pdf file Use the below python script to get the count of words in any pdf file.
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 56 | #!/usr/bin/env python3 import os import sys import re import time import PyPDF2 def getPageCount(pdf_file): pdfFileObj = open(pdf_file, 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) pages = pdfReader.numPages return pages def extractData(pdf_file, page): pdfFileObj = open(pdf_file, 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) pageObj = pdfReader.getPage(page) data = pageObj.extractText() return data def getWordCount(data): data=data.split() return len(data) def main(): if len(sys.argv)!=2: print('command usage: python word_count.py FileName') exit(1) else: pdfFile = sys.argv[1] # check if the specified file exists or not try: if os.path.exists(pdfFile): print("file found!") except OSError as err: print(err.reason) exit(1) # get the word count in the pdf file totalWords = 0 numPages = getPageCount(pdfFile) for i in range(numPages): text = extractData(pdfFile, i) totalWords+=getWordCount(text) time.sleep(1) print (totalWords) if __name__ == '__main__': main() |
Hope this answer helps!
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.