Showing posts with label word count. Show all posts
Showing posts with label word count. Show all posts

Java - File handling - line, word and character count


// File handling

/*
Write a Java program that displays the number of characters, lines and words in a text file.
*/

import java.io.*;

class FileLWC
{
     public static void main(String as[]) throws IOException
     {
         
          FileInputStream fin = new FileInputStream("ipt.txt");
          int lc = 0, wc = 0, cc = 0;
         
          while(true)
          {
              int i = fin.read();
              if(i==-1)
              {
                   lc++;
                   wc++;
                   break;
              }
              char c = (char)i;
             
              if(c=='\n' || c=='.')
              {
                   lc++;
                   wc++;
              }
              else if(c=='\t' || c==' ')
                   wc++;
              else if((c>='a' && c<='z')||(c>='A' && c<='Z'))
                   cc++;
                            
          }       
          System.out.println("Line count = "+lc);
          System.out.println("Word count = "+wc);
          System.out.println("Character count = "+cc);
          fin.close();
     }
}

File Handling 13: Count number of occurances of a word in a file

# Count number of times a word exists in a file

fs = open("ipt.txt", "r")
search_str = input("Enter string to search : ").strip().lower()
counter = 0

while(True):
Line = fs.readline().strip().lower()

if not Line:
break

counter += Line.count(search_str)

if(counter):
print(search_str, "present in file", counter , "times")
else:
print(search_str, "not present in file")

fs.close()

File Handling 11: File line, word and character count

# Count number of characters, words and lines in a file
# File Count

fs = open("ipt.txt", "r")

charcount = 0
wordcount = 0
linecount = 0

all_lines = fs.readlines()
linecount = len(all_lines)

for Line in all_lines:
Line = Line.strip().lower()

tmp = Line.split(" ")
wordcount += len(tmp)

for ch in Line:
if(ch.isalpha()):
charcount += 1

print("Number of characters in file =", charcount)
print("Number of words in file =", wordcount)
print("Number of lines in file =", linecount)

fs.close()