Ejercicio
Contar Caracteres En Un Archivo De Texto
Objectivo
Desarrollar un programa Python que cuente cuántas veces aparece un carácter específico en un archivo determinado (de cualquier tipo).
El programa debe permitir al usuario ingresar el nombre del archivo y el carácter que se desea buscar, o bien estos pueden pasarse como argumentos de la línea de comandos:
Ejemplo:
count example.txt a
El programa debe mostrar la cantidad de veces que aparece el carácter especificado.
(Siéntase libre de diseñar la interacción del usuario y mostrar la guía adecuada si es necesario).
Ejemplo de ejercicio de Python
Mostrar código Python
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.
Código de ejemplo copiado
Comparte este ejercicio de Python