Ejercicio
Texto censurado
Objetivo
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.
Código
Imports System
Imports System.IO
Class TextCensorer
Private Shared Function CreateDictionary(ByVal fileName As String) As String()
Dim result As String()
Dim inputFile As StreamReader
Dim line As String
Dim numLines As Integer = 0
If File.Exists(fileName) Then
Try
inputFile = File.OpenText(fileName)
Do
line = inputFile.ReadLine()
If line IsNot Nothing Then numLines += 1
Loop While line IsNot Nothing
inputFile.Close()
result = New String(numLines - 1) {}
inputFile = File.OpenText(fileName)
Dim currentLineNumber As Integer = 0
Do
line = inputFile.ReadLine()
If line IsNot Nothing Then
result(currentLineNumber) = line
currentLineNumber += 1
End If
Loop While line IsNot Nothing
inputFile.Close()
Return result
Catch __unusedException1__ As Exception
Return Nothing
End Try
End If
Return Nothing
End Function
Private Shared Sub Main(ByVal args As String())
Dim inputFile As StreamReader
Dim outputFile As StreamWriter
Dim line As String
Dim name As String
If args.Length < 1 Then
Console.WriteLine("Not enough parameters!")
Console.Write("Enter file name: ")
name = Console.ReadLine()
Else
name = args(0)
End If
If Not File.Exists(name) Then
Console.WriteLine("File not found!")
Return
End If
Try
Dim wordsList As String() = CreateDictionary("dictionary.txt")
inputFile = File.OpenText(name)
outputFile = File.CreateText(name & ".censored")
Do
line = inputFile.ReadLine()
If line IsNot Nothing Then
For Each censoredWord As String In wordsList
If line.Contains(" " & censoredWord & " ") Then line = line.Replace(" " & censoredWord & " ", " [CENSORED] ")
If line.Contains(" " & censoredWord & ".") Then line = line.Replace(" " & censoredWord & ".", " [CENSORED].")
If line.Contains(" " & censoredWord & ",") Then line = line.Replace(" " & censoredWord & ",", " [CENSORED],")
If line.EndsWith(" " & censoredWord) Then
line = line.Substring(0, line.LastIndexOf(" " & censoredWord))
line += " [CENSORED]"
End If
Next
outputFile.WriteLine(line)
End If
Loop While line IsNot Nothing
inputFile.Close()
outputFile.Close()
Catch __unusedPathTooLongException1__ As PathTooLongException
Console.WriteLine("Entered path was too long")
Return
Catch ex As IOException
Console.WriteLine("Input/output error: {0}", ex.Message)
Return
Catch ex As Exception
Console.WriteLine("Unexpected error: {0}", ex.Message)
Return
End Try
End Sub
End Class