Program to count lines, words, characters and spaces in the given file using Python

by | Jul 24, 2021 | Python Programs

Introduction

In this program we will learn how to count lines, words, characters and spaces in a given file. All these will be calculated and shown altogether.

Program

Approach 1

def read(file): 
    countWords, countLines, countChar, countSpace  = 0,0,0,0
    with open(file, 'r') as readFile: 
        for readLine in readFile: 
            countLines += 1
            val = 'Y' 
            for readWord in readLine: 
                if (readWord != ' ' and val == 'Y'):  
                    countWords += 1 
                    val = 'N' 
                elif (readWord == ' '): 
                    countSpace += 1 
                    val = 'Y'
                for readChar in readWord: 
                    if(readChar !=" " and readChar !="\n"): 
                        countChar += 1
    print("Line count", countLines) 
    print("Word count: ", countWords)      
    print("Char count", countChar)  
    print("Space count", countSpace) 
file = 'demo.txt'
read(file)

Output:

Program to count lines, words, characters and spaces in the given file using Python Output 1

Approach 2

import os 
def read(file): 
    countWords, countLines, countChar, countSpace  = 0,0,0,0
    with open(file, 'r') as readFile: 
        for readline in readFile: 
            readline = readline.strip(os.linesep) 
            list = readline.split() 
            countLines = countLines + 1
            countWords = countWords + len(list) 
            countChar = countChar + sum(1 for c in readline  
                          if c not in (os.linesep, ' ')) 
            countSpace = countSpace + sum(1 for s in readline  
                                if s in (os.linesep, ' ')) 
    print("Line count", countLines) 
    print("Word count: ", countWords)      
    print("Char count", countChar)  
    print("Space count", countSpace) 
file = 'demo.txt'
read(file)  

Output:

Program to count lines, words, characters and spaces in the given file using Python Output 

Explanation

Approach 1:

  • Open file using open() function.
  • Increment line count by 1 for each loop.
  • Increment word count, char count and space count depending upon the condition and return the respective values.

Approach 2:

  • To separate lines we have used os.linesep() function of OS module.
  • Python in-built function strip() and split() is used to extract the words, characters and counters are incremented.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.