Question 7 - Past Year - 2 Mark Questions - Chapter 2 - File Handling in Python
Last updated at May 29, 2023 by Teachoo
A text file “PARA.txt” contains a paragraph. Write a function that searches for a given character and reports the number of occurrence of the character in the file.
Answer:
def count_alpha():
c=0
x=input("Enter character to search for: ")
f=open("PARA.txt",'r')
l=f.readlines()
for
line in l:
for
word in line:
for
char in word:
if
char == x:
c=c+1
print("Number of occurrences of "+x+" = "+str(c))
f.close()
Learn in your speed, with individual attention - Teachoo Maths 1-on-1 Class
Question 7 A text file “PARA.txt” contains a paragraph. Write a
function that searches for a given character and reports the number of occurrence of the character in the file.
declaring function count_alpha( )
Accepts a user input and assigns it to ‘x’
reading all the lines in the text file and assigning it to ‘l’
Iterating through each line in ‘l’ and assigning it to ‘line’
Iterating through each character in a word and assigning it to ‘char’
If a character matches, then increase the value of ‘c’ by 1
Invoking function count_alpha( )
Assigning a variable ‘c’ with value 0
Opening the text file in read mode and assigning it to file_object ‘f’
Iterating through each word in a line and assigning it to ‘word’
Checking if a character matches the value assigned to ‘x’
Prints the number of occurrences
Closing the file
Output
Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 13 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.
Hi, it looks like you're using AdBlock :(
Displaying ads are our only source of revenue. To help Teachoo create more content, and view the ad-free version of Teachooo... please purchase Teachoo Black subscription.
Please login to view more pages. It's free :)
Teachoo gives you a better experience when you're logged in. Please login :)
Solve all your doubts with Teachoo Black!
Teachoo answers all your questions if you are a Black user!