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

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 program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...