Programmin-in-Python

Counting Characters in a File

Dec 14th, 2020 (edited)
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. from string import ascii_letters, ascii_lowercase, ascii_uppercase
  2.  
  3. def count_characters(stream):
  4.     no_small = 0
  5.     no_block = 0
  6.     no_special = 0
  7.     no_vowel = 0
  8.     no_consonant = 0
  9.     no_numbers = 0
  10.  
  11.     for lines in stream:
  12.         for word in lines:
  13.             if word in ascii_letters :
  14.                 if word in ascii_uppercase : no_block += 1
  15.                 if word in ascii_lowercase : no_small += 1
  16.                 if word.lower() in ("a","e","i","o","u") : no_vowel += 1
  17.                 if word.lower() not in ("a","e","i","o","u") : no_consonant += 1
  18.             elif ord("0") <= ord(word) <= ord("9") : no_numbers += 1
  19.             else : no_special += 1
  20.  
  21.     return no_small, no_block, no_special, no_vowel, no_consonant, no_numbers
  22.  
  23. def main():
  24.     filename = input("Please Enter the Path of the File : ") #Enter the full File path (/home/usr/Documents/file1.dat)
  25.     filetype = input("Is it a Text File (Y/n) : ")
  26.  
  27.     try :
  28.         if filetype.lower() == "y" : file = open(filename)
  29.         elif filetype.lower() == "n" : file = open(filename, "rb")
  30.         else : print("Invalid Choice\nExiting...")
  31.  
  32.         data = file.readlines()
  33.         no_small, no_block, no_special, no_vowel, no_consonant, no_numbers = count_characters(data)
  34.         print("\nThe File Contains\nNo. of Small Letters : ", no_small)
  35.         print("No. of BLOCK Letters : ", no_block)
  36.         print("No. of Vowels : ", no_vowel)
  37.         print("No. of Consonants : ", no_consonant)
  38.         print("No. of Numbers : ", no_numbers)
  39.         print("No. of Special Characters : ", no_special)
  40.  
  41.     except FileNotFoundError : print("Oops!!! Such a File does not Exists...")
  42. main()
Add Comment
Please, Sign In to add comment