by BehindJava
Write a program to read a Text File and Counts the Number of Times a Certain Letter Appears in the Text File in Python
In this tutorial we are going to learn about reading a Text File and Counts the Number of Times a Certain Letter Appears in the Text File in Python.
Python Program that Reads a Text File and Counts the Number of Times a Certain Letter Appears in the Text File
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)
Explanation
- User must enter a file name and the letter to be searched.
- The file is opened using the open() function in the read mode.
- A for loop is used to read through each line in the file.
- Each line is split into a list of words using split().
- 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.
- If the letter provided by the user and the letter encountered over iteration are equal, the letter count is incremented.
- The final count of occurrences of the letter is printed.