Worksheet
Q1. Write a user-defined function count_words() in Python to read
the contents of a text file "[Link]" and count how many times
the word "the" occurs (ignoring case details).
def count_words():
file = open("[Link]", "r")
content = [Link]()
words = [Link]()
count = 0
for w in words:
if [Link]() == "the":
count += 1
print("Total occurrences of 'the':", count)
[Link]()
2. Write a function readstar() that reads a text file [Link] and display
line numbers that contains * anywhere. For example, the file contains
The multiplication symbol * has many meaning The *
can also be used as pointer
The addition symbol + also has many meaning
The output of the readstar() should be
Line no 1 has star Line no 2 has star.
Ans. def readstar():
f=open(“[Link]”,”r”)
l=[Link]() # it will return list of lines
count=0
for x in l:
count=count+1
if x in “*”:
print(“Line no “, count, “ has star”)
3. Write a function word5count() that count number of words whose length
is more than 5 characters in above given [Link] file.
def word5count():
f=open(“[Link]”,”r”)
s=[Link]()
l=[Link]()
count=0
for x in l:
if len(x)>5:
count=count+1
print(“ total words having length more then 5 are “, count)
4. Write a function in Python to count the number of lines in a text
fie ‘[Link]’ which start with an alphabet ‘T’ .
Ans. def count_lines():
count = 0
file=open("[Link]", "r")
for line in file:
if [Link]('T'):
count += 1
print("Number of lines starting with 'T' =", count)
5. Write a method in Python to read lines from a text file
[Link], to find and display the occurrence of the word 'are'. For
example, if the content of the file is:
Books are referred to as a man’s best friend. They are very
beneficial for mankind and have helped it evolve. Books leave a
deep impact on us and are responsible for uplifting our mood.
The output should be 3.
Ans. def count_are():
count = 0
f=open("[Link]", "r")
for line in file:
words = [Link]()
for word in words:
if [Link](".,!?;:").lower() == "are":
count += 1
print("Occurrence of 'are' =", count)
count_are()