Count the number of words in a file

This is a simple Python script to count the number of words in file.

The program imports counter class from Python library collections and uses counter class to count the number words in a file. This program uses various built in functions:

  • split(<str>, <num>): The method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.
  • update(): The method update() add extra details to the given dictionary.
  • values(): The method values() returns a list of all the values available in a given dictionary.

This program prompts the user to input a file name. The file is opened in readonly mode and using the counter class counts the words in a file.

# Python program to count the number of words in file

# importing counter class from python library collections.
from collections import Counter

fname = str(input("Input a file name : "))
c = Counter()
# Open file in read only mode
with open(fname, 'r') as f:
    for ln in f:
        c.update(ln.split())

total = sum(c.values())
total += 1
print("The file", fname, "contains", total, "words.")

Program Output

Input a file name : c:\myInputFile.txt
The file c:\myInputFile.txt contains 28 words.
>>> 


Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Nothing yet..be the first to share wisdom.