Ejercicio
Modificador De Texto
Objectivo
Desarrolla un programa Python que lea un archivo de texto, reemplace las palabras especificadas y guarde el contenido modificado en un nuevo archivo.
El programa debe aceptar el nombre del archivo, la palabra de destino y la palabra de reemplazo como parámetros de la línea de comandos:
Ejemplo de comando:
replace_text file.txt hello goodbye
El resultado se guardará en un archivo llamado "file.txt.out", donde cada instancia de "hello" se reemplaza por "goodbye".
Ejemplo de ejercicio de Python
Mostrar código Python
import sys
def replace_text_in_file(file_name, target_word, replacement_word):
"""
Reads a text file, replaces all occurrences of the target word with the replacement word,
and saves the modified content into a new file named 'file_name.out'.
Parameters:
file_name (str): The name of the input file to read.
target_word (str): The word to be replaced.
replacement_word (str): The word to replace the target word with.
"""
try:
# Open the input file in read mode
with open(file_name, 'r') as file:
# Read all the lines from the file
content = file.read()
# Replace all occurrences of target_word with replacement_word
modified_content = content.replace(target_word, replacement_word)
# Create the output file name by appending '.out' to the original file name
output_file_name = file_name + '.out'
# Open the output file in write mode and save the modified content
with open(output_file_name, 'w') as output_file:
output_file.write(modified_content)
print(f"Modification successful! The modified content has been saved to '{output_file_name}'")
except FileNotFoundError:
print(f"The file '{file_name}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Main program execution
if __name__ == "__main__":
# Check if the correct number of arguments are provided
if len(sys.argv) != 4:
print("Usage: replace_text ")
else:
# Extract command-line arguments
file_name = sys.argv[1]
target_word = sys.argv[2]
replacement_word = sys.argv[3]
# Call the replace_text_in_file function
replace_text_in_file(file_name, target_word, replacement_word)
Output
Assume file.txt contains the following text:
hello world
hello there
hello again
If you run the following command:
python replace_text.py file.txt hello goodbye
The program will create a new file, file.txt.out, with the following content:
goodbye world
goodbye there
goodbye again
Código de ejemplo copiado
Comparte este ejercicio de Python