How to have python read a text file and return the number of lines
, characters
, vowels
, consonants
, lowercase letters
, and uppercase letters
Write a program that accepts the name of a file as a command-line argument. (You can assume that the input file will be a plain-text file.) If the user forgets to include the command line argument, your program should exit with an appropriate error message.
Otherwise, your program should print out:
- The number of lines in the file
- The number of characters in the file
- The number of vowels in the file (For the purposes of this assignment, treat "y" as a consonant.)
- The number of consonants in the file
- The number of lowercase letters in the file
- The number of uppercase letters in the file
I am at a lose. How would I do this? like im pretty sure there are commands that can do this but I dont know what they are. Thanks for your help :)
EDIT This is my final program and its perfect. Thank you all for your help. Special thanks to Bentaye :)
import sys
def text():
countV = 0
countC = 0
lines = 0
countU = 0
countL = 0
characters = 0
vowels = set("AEIOUaeiou")
cons = set("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ")
upper = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
lower = set("abcdefghijklmnopqrstuvwxyz")
with open(sys.argv[1]) as file:
fileLines = file.readlines()
for line in fileLines:
lines = lines + 1
characters = characters + len(line)
for char in line:
if char in vowels:
countV = countV + 1
elif char in cons:
countC = countC + 1
for char in line:
if char in upper:
countU = countU + 1
elif char in lower:
countL = countL + 1
print("Lines: " + str(lines))
print("Characters: " + str(characters))
print("Vowels: " + str(countV))
print("Consonants: " + str(countC))
print("Lowercase: " + str(countL))
print("Uppercase: " + str(countU))
text()