Assignment Text 2 Key
Assignment Text 2 Key
It
will not make any difference, just write the code within body of the function. No need to
call the function.
For example the question in previous assignment was :
Program-b: Count number of lines in file myfile.txt.
IF same program was: to write a function CountLines() in python to count and print number
of lines in file “myfile.txt”. Then answer would be.
def CountLines(): // the only difference
fin=open("myfile.txt",'r')
str=fin.readlines()
count_line=0
print(len(str))
for i in str:
count_line=count_line+1
print(“Number of Lines in file: “,count_line)
fin.close( )
TEST
Now Attempt following questions:
The contents of file “STORY.TXT”, used in some questions may be considered as:
Q1. Write a function CountUcase() in python to read text file “STORY.TXT”, count and print the
number of uppercase alphabets present in the file.
The Countucase( ) function should display the output as:
Upper Case characters= 8
def Countucase( ):
f=open("STORY.TXT ",'r')
str=f.read()
c=0
for i in str:
if i.isupper():
c+=1
print("Upper Case characters = ",c)
Q2. Write a function in python to read text file “STORY.TXT”, count and print the number of
spaces and commas present in the file.
def count():
f=open("STORY.TXT ",'r')
str=f.read()
s=0
c=0
for i in str:
if i.isspace():
s+=1
elif i==',':
c+=1
print("Spaces = ",s)
print("Commas = ",c)
Q3. Write a function CountMyThe() in python to read text file “STORY.TXT”, count and print the
number of occurrences of words “my” and “the” in the file.
Q6. Write a method/function DISPLAYWORDS() in python to read lines from a text file
STORY.TXT, and display words having less than 4 characters.
Q7. Write a python code to find the size of the file in bytes, number of lines and number of words.
# reading data from a file and find size, lines, words
f=open(‘Lines.txt’,’r’)
str=f.read( )
size=len(str)
print(‘size of file n bytes’,size)
f.seek(0)
L=f.readlines( )
word=L.split( )
print(‘Number of lines ’,len(L))
print(‘Number of words ’,len(word))
f.close( )
Q8. Write function to print just the last word of a text file “data.txt”.
Ans:
def print_last():
fin=open(“data.txt”,”r”)
S=fin.read()
L=S.split()
print(“Last word = “,L[-1])
fin.close()
Q9. Write a function countVowel() to read the file “story.txt” and print number of lower case vowels
in each word of the file.
def countVowel():
fin=open("myfile.txt",'r')
str=fin.read()
L=str.split()
if x in [„a‟,‟e‟,‟i‟,‟o‟,‟u‟]:
p=p+1
fin.close( )