Python Program to Counts the Number of Times a Letter Appears in the Text File

This python program counts the occurrences of a specific letter in a text file.

Problem statement

This program begins with an introduction that explains its purpose. It then takes the path to the text file and the target letter as inputs from the user. The program reads the file, cleans the content by removing punctuation and converting to lowercase, and counts the occurrences of the target letter.

Python Program to Counts the Number of Times a Letter Appears in the Text File

import string
file_path = input("\nEnter the path to the text file: ")
target_letter = input("Enter the letter to count: ")
try:
    with open(file_path, 'r') as file:
        content = file.read()
        cleaned_content = content.translate(str.maketrans('', '', string.punctuation))
        cleaned_content = cleaned_content.lower()
        letter_count = cleaned_content.count(target_letter.lower())
        print(f"The letter '{target_letter}' appears {letter_count} times in the text file.")
except FileNotFoundError:
    print("File not found.")

How it works

  1. The program will prompt you to enter the path to a text file.
  2. You’ll then input a letter for which you want to count occurrences.
  3. The program reads the file, processes its content, and counts how many times the given letter appears.
  4. Finally, the program displays the count of occurrences of the letter in the text file.

Input / Output

Python Program to Counts the Number of Times a Letter Appears in the Text File

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this python tutorial, you will learn how to Display Prime Numbers Between Two Intervals using the if and else...
In this python tutorial, you will learn how to Calculate Standard Deviation with built in functions of the python programming...
In this Python program, we will convert temperature values from Celsius to Fahrenheit. The Celsius and Fahrenheit scales are two...