Ejercicio
Texto Censurado
Objectivo
Cree un programa para "censurar" archivos de texto. Debe leer un archivo de texto y volcar sus resultados a un nuevo archivo de texto, reemplazando ciertas palabras con "[CENSURADO]". Las palabras a censurar se almacenarán en un segundo archivo de datos, un archivo de texto que contendrá una palabra en cada línea.
Ejemplo Ejercicio C#
Mostrar Código C#
// Importing necessary namespaces
using System;
using System.Collections.Generic;
using System.IO;
class TextCensorship
{
// Main method where the program execution begins
static void Main()
{
// Path to the input text file that will be censored
string inputFilePath = "input.txt";
// Path to the file containing the words to be censored (one word per line)
string censorFilePath = "censorship_list.txt";
// Path to the output file where the censored text will be written
string outputFilePath = "output.txt";
// Call the CensorText method to process the file and censor the words
CensorText(inputFilePath, censorFilePath, outputFilePath);
}
// Method to read the input file, censor words, and write the result to a new file
static void CensorText(string inputFilePath, string censorFilePath, string outputFilePath)
{
try
{
// Read the words to censor from the censorship list file
HashSet wordsToCensor = new HashSet(File.ReadAllLines(censorFilePath));
// Read the input text file into a string
string inputText = File.ReadAllText(inputFilePath);
// Loop through each word to censor and replace it with "[CENSORED]"
foreach (var word in wordsToCensor)
{
// Replace all occurrences of the word (case-insensitive)
inputText = inputText.Replace(word, "[CENSORED]", StringComparison.OrdinalIgnoreCase);
}
// Write the censored text to the output file
File.WriteAllText(outputFilePath, inputText);
Console.WriteLine("Text has been censored and written to the output file.");
}
catch (Exception ex)
{
// Catch any errors (e.g., file not found or read/write issues) and display an error message
Console.WriteLine("Error: " + ex.Message);
}
}
}
Salida
input.txt file: Contains the text to be censored. For example:
This is a simple text with some bad words like badword1 and badword2.
We don't want badword1 or badword2 to appear in the output.
censorship_list.txt file: Contains the words to be censored. Example:
badword1
badword2
output.txt file: Will contain the censored text, where all the words specified in censorship_list.txt are replaced with "[CENSORED]". The content of the output file would be:
This is a simple text with some [CENSORED] words like [CENSORED] and [CENSORED].
We don't want [CENSORED] or [CENSORED] to appear in the output.
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp