This is a Python Program to count the occurrences of a letter in a text file.
VARISHA PARVEZ
Asked: May 1, 20232023-05-01T07:25:54+00:00
2023-05-01T07:25:54+00:00In: Programs/Codes
This is a Python Program to count the occurrences of a letter in a text file.
Share
Related Questions
- Which of the following algorithms is used to find the topological ordering of a directed acyclic graph? a) Depth-First ...
- Which of the following is not a type of algorithm paradigm? a) Greedy algorithms b) Divide and Conquer algorithms c) ...
- Which of the following is a greedy algorithm used for finding the minimum spanning tree in a graph? a) ...
- Which of the following is not an example of a greedy algorithm? a) Huffman coding b) Activity selection problem c) ...
- Which of the following algorithms can be used to find the maximum flow in a flow network? a) Kruskal's algorithm ...
Problem Description
The program takes a letter from the user and counts the number of occurrences of that
letter in a file.
Problem Solution
1. Take the file name and the letter to be counted from the user.
2. Read each line from the file and split the line to form a list of words.
3. Use a for loop to traverse through the words in the list and another for loop to traverse
through the letters in the word.
4. Check if the letter provided by the user and the letter encountered over iteration is
equal and if they are, increment the letter count.
5. Exit.
Program/Source Code
Here is source code of the Python Program to count the occurrences of a letter in a text
file. The program output is also shown below.
fname = input(“Enter file name: “)
l=input(“Enter letter to be searched:”)
k = 0
with open(fname, ‘r’) as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter==l):
k=k+1
print(“Occurrences of the letter:”)
print(k)
Program Explanation
1. User must enter a file name and the letter to be searched.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. Each line is split into a list of words using split().
5. A for loop is used to traverse through the words list and another for loop is used to traverse through
the letters in the word.
6. If the letter provided by the user and the letter encountered over iteration are equal, the letter count
is incremented.
7. The final count of occurrences of the letter is printed.
Runtime Test Cases
Case 1:
Contents of file:
hello world hello
hello
Output:
Enter file name: out.txt
Enter letter to be searched:o
Occurrences of the letter:
5
Case 2:
Contents of file:
hello world
test
test test
Output:
Enter file name: out1.txt
Enter letter to be searched:e
Occurrences of the letter:
6