SoFunction
Updated on 2024-10-29

Python's method for counting the number of words in a file

This article is an example of how Python calculates the number of words in a file. Shared for your reference. Specific as follows:

This program finds the number of words from the given document.

from string import *
def countWords(s):
  words=split(s)
  return len(words)
  #returns the number of words
filename=open("",'r')
#open an file in reading mode
total_words=0
for line in filename:
  total_words=total_words + countWords(line)
  #counts the total words
print total_words

I hope that what I have described in this article will help you in your Python programming.