Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

LAB TASK 8

PROGRAMMING EXERCISES:
Question 1.
Write a function stats() that takes one input argument: the name of a text file. The
function should print, on the screen, the number of lines, words, and characters in the file.Your
function should open the file only once

stats('example.txt') >>>
line count: 3 word count: 20 character count: 98
Program:
import os
def stats(filename):
f=open(filename,"r")
content=f.read()
f.close()
lines=content.split("\n")
words = content.split()
print("Number of lines =", len(lines))
print("Number of words =", len(words))
print("Number of characters =",len(content)-(len(lines)-1))

stats("c:\sample\my.txt")

Result:
Number of lines = 3
Number of words = 10
Number of characters = 40

Question 2
Implement function distribution() that takes as input the name of a file (as a string). This one-
line file will contain letter grades separated by blanks. Your function should print the
distribution of grades.
Program:
def distribution(filename):
f=open(filename,"r")
content=f.read()
f.close()
grade_list=content.split(" ")
dict={}
lst=["A","A-","B+","B","B-","C","C-","F"]
for i in range(len(lst)):
dict[lst[i]]=grade_list.count(lst[i])
for x,y in dict.items():
print("Students who got",x,"=",y)
distribution("c:\sample\grades.txt")

Result:
Students who got A = 6
Students who got A- = 2
Students who got B+ = 3
Students who got B = 2
Students who got B- = 2
Students who got C = 4
Students who got C- = 1
Students who got F = 2
Question 3.
Implement function duplicate() that takes as input the name (a string) of a file in the current
directory and returns True if the file contains duplicate words and False otherwise.

Program:
def duplicate(filename):
f=open(filename,"r")
content=f.read()
f.close()
word_list=content.split()
for i in range(len(word_list)):
if word_list[i] in word_list[i+1:]:
print(True)
break
else:
print(False)
duplicate("c:\sample\my.txt")

Result:
True

Question 4.
The function abc() takes the name of a file (a string) as input. The function should open the file,
read it, and then write it into file abc.txt with this modification: Every occurrence of a four-letter
word in the file should be replaced with string ‘xxxx’
Note that this function produces no output, but it does create file abc.txt in the current folder.
Program:
import os
def abc(filename):
f=open(filename,"r+")
content=f.read()
f.close()
f1=open('c:\sample\kab.txt', "a")
word_list=content.split()
for i in range(len(word_list)):
if len(word_list[i])==4:
word_list[i]="XXXX"
f1.write(" ".join(word_list))
f1.close()
abc("c:\sample\my.txt")

Result:
Before:

After:

You might also like