
File reading: Character By Character
Question: 6
write a (python script) function named count_digit() to read the contents of the file “story.txt”. Further, count and print total digit in the file.
Sol:
def count_digit():
d=0
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if(c>='0' and c<='9'):
d=d+1
print("total digits ",d)
#function calling
count_digit()
Question : 7
write a (python script) function named count_vowels() to read the contents of the file “story.txt”. Further count and print total vowels in the file.
Sol:
def count_vowels():
d=0
vowels="aeiouAEIOU"
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if(c in vowels):
d=d+1
print("total digits ",d)
#function calling
count_vowels()
Question: 8
write a (python script) function named count_consonants() to read the contents of the file “story.txt”. Further, count and print total consonants in the file.
Sol:
def count_consonants():
c1=0
vowels="aeiouAEIOU"
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if((c>='A' and c<='Z') or(c>='a' and c<='z')):
if not (c in vowels):
c1=c1+1
print("total consonants ",c1)
#function calling
count_consonants()

Question : 9
write a (python script) function named count() to read the contents of the file “story.txt”. Further count and print the following:
#total length
#total alphabets
#total vowels
#total conbsonants
#total non alpha chars
Sol:
def count():
d=0
le=0
c1=0
c2=0
a=0
vowels="aeiouAEIOU"
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
le=le+1
if((c>='A' and c<='Z') or(c>='a' and c<='z')):
a=a+1
if (c in vowels):
d=d+1
else:
c1=c1+1
c2=c2+1
print("total vowels ",d)
print("total consonants ",c1)
print("total alphabets ",a)
print("total chars which are not alphabets ",c2)
print("length = ",le)
#function calling
count()
Question: 10
write a (python script) function named count_spaces() to read the contents of the file “story.txt”. Further count and print total spaces in the file.
Sol:
def count_space():
d=0
space=" "
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if(c in space):
d=d+1
print("total spaces ",d)
#function calling
count_space()




