Exercise
Count Characters In A Text File
Objective
Develop a Python program that counts how many times a specific character appears in a given file (of any type).
The program should allow the user to input the file name and the character to search for, or these can be passed as command-line arguments:
Example:
count example.txt a
The program should display the count of occurrences of the specified character.
(Feel free to design the user interaction and display appropriate guidance if needed.)
Example Python Exercise
Show Python Code
import sys
def count_character_in_file(file_name, character):
"""
Counts how many times a specific character appears in a given file.
Parameters:
file_name (str): The name of the file to search.
character (str): The character to search for in the file.
Returns:
int: The count of occurrences of the specified character.
"""
count = 0
try:
# Open the file in read mode
with open(file_name, 'r') as file:
# Read the content of the file
content = file.read()
# Count the occurrences of the specified character
count = content.count(character)
return count
except FileNotFoundError:
print(f"The file '{file_name}' was not found.")
return -1 # Indicates file was not found
except Exception as e:
print(f"An error occurred: {e}")
return -1 # Indicates an unexpected error
# Main program execution
if __name__ == "__main__":
# Check if the correct number of arguments are provided
if len(sys.argv) == 3:
# Extract command-line arguments
file_name = sys.argv[1]
character = sys.argv[2]
# Validate that only one character is provided
if len(character) != 1:
print("Please provide exactly one character to search for.")
else:
# Call the function to count the character in the file
count = count_character_in_file(file_name, character)
if count != -1:
print(f"The character '{character}' appears {count} times in the file '{file_name}'.")
else:
# Ask the user for the file name and character if no command-line args
file_name = input("Please enter the file name: ")
character = input("Please enter the character to search for: ")
# Validate that only one character is provided
if len(character) != 1:
print("Please provide exactly one character to search for.")
else:
# Call the function to count the character in the file
count = count_character_in_file(file_name, character)
if count != -1:
print(f"The character '{character}' appears {count} times in the file '{file_name}'.")
Output
Assume example.txt contains:
apple
banana
avocado
If you run the following command:
python count_character.py example.txt a
The program will output:
The character 'a' appears 6 times in the file 'example.txt'.
If the file does not exist or an error occurs, the program will display:
The file 'nonexistent.txt' was not found.
Share this Python Exercise