2012-09-11 10 views
8

Estoy creando una aplicación que convierte texto en Braille. Convertirme en Braille no es un problema, pero no sé cómo convertirlo.Reemplazar números de char después de un char específico

Ejemplo 1: Conversión de números a Braille

1  = #a 
123 = #abc 
12 45 = #ab #de 

Ejemplo 2: Conversión de capitales a Braille

Jonas = ,jonas 
JONAS = ,,jonas 

I tienen un problema de la conversión de Braille de nuevo a normal. No puedo simplemente convertir cada a a 1 y así sucesivamente. Los números se pueden verificar mediante el # y luego cambiar los caracteres después de él al siguiente espacio, pero no sé cómo. La coma antes de la letra es más difícil de separar de otras comas en el texto.

Aquí es mi clase para la conversión a Braille:

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Drawing; 

namespace BrailleConverter 
{ 
    class convertingBraille 
    { 
     public Font getIndexBrailleFont() 
     { 
      return new Font("Index Braille Font", (float)28.5, FontStyle.Regular); 
     } 

     public Font getPrintableFontToEmbosser() 
     { 
      return new Font("Lucida Console", (float)28.5, FontStyle.Regular); 
      //return new Font("Index Black Text Font", (float)28.5, FontStyle.Regular); 
     } 

     public string convertCapitalsToUnderscore(string text) 
     { 
      if (string.IsNullOrEmpty(text)) 
      { 
       return ""; 
      } 

      text = " " + text; 

      text = text.Replace('.', '\''); 
      text = text.Replace(',', '1'); 
      text = text.Replace('?', '5'); 
      text = text.Replace('!', '6'); 
      text = text.Replace(':', '3'); 
      text = text.Replace('=', '7'); 
      text = text.Replace('+', '4'); 
      text = text.Replace('*', '9'); 
      text = text.Replace('é', '='); 

      StringBuilder newText = new StringBuilder(text.Length * 2); 
      newText.Append(text[0]); 

      bool firstCapLetterInWord = true; 

      for (int i = 1; i < text.Length; i++) 
      { 
       char letter = text[i]; // Aktuell bokstav 
       char nextLetter = ' '; // Nästa bokstav 

       try 
       { 
        nextLetter = text[i + 1]; 
       } 
       catch 
       { 

       } 

       // Är det stor bokstav? 
       if (char.IsUpper(letter)) 
       { 
        // Är nästa bokstav stor? 
        if (char.IsUpper(nextLetter)) 
        { 
         // Är det början av ett helt ord med caps? 
         if (firstCapLetterInWord) 
         { 
          newText.Append(",,"); // 2 st understräck framför ordet 

          firstCapLetterInWord = false; // Ändra så att inte nästa bokstav får 2 st understräck 
         } 
        } 
        else // Annars bara ett understräck 
        { 
         if (firstCapLetterInWord) 
         { 
          newText.Append(","); // Sätt understräck framför bokstav 
         } 

         firstCapLetterInWord = true; // Förbereda för nästa capsord 
        } 
       } 

       newText.Append(text[i]); 
      } 

      string finishedText = newText.ToString().TrimStart(); // Ta bort mellanslaget i början 

      finishedText = finishedText.ToLower(); 

      finishedText = finishedText.Replace('å', '*'); 
      finishedText = finishedText.Replace('ä', '>'); 
      finishedText = finishedText.Replace('ö', '['); 

      return finishedText; 
     } 

     public string convertNumbersToBrailleNumbers(string text) 
     { 
      if (string.IsNullOrEmpty(text)) 
      { 
       return ""; 
      } 

      text = " " + text; 

      StringBuilder newText = new StringBuilder(text.Length * 2); 
      newText.Append(text[0]); 

      bool firstNumberInNumber = true; 

      for (int i = 1; i < text.Length; i++) 
      { 
       char letter = text[i]; // Aktuell tecken 
       char nextLetter = ' '; // Nästa tecken 

       try 
       { 
        nextLetter = text[i + 1]; 
       } 
       catch 
       { 

       } 

       char convertedChar = text[i]; 

       // Är tecknet en siffra? 
       if (char.IsNumber(letter)) 
       { 
        // Är nästa tecken en siffra? 
        if (char.IsNumber(nextLetter)) 
        { 
         // Är det början av ett flertaligt nummer? 
         if (firstNumberInNumber) 
         { 
          newText.Append('#'); // Brädkors framför nummret 

          firstNumberInNumber = false; // Ändra så att inte nästa siffra får brädkors 
         } 
        } 
        else // Annars bara ett understräck 
        { 
         if (firstNumberInNumber) 
         { 
          newText.Append('#'); // Sätt brädkors framför siffran 

         } 

         firstNumberInNumber = true; // Förbereda för nästa flertaliga nummer 
        } 
       } 

       newText.Append(convertedChar); 
      } 

      string finishedText = newText.ToString().TrimStart(); 

      finishedText = finishedText.Replace('1', 'a'); 
      finishedText = finishedText.Replace('2', 'b'); 
      finishedText = finishedText.Replace('3', 'c'); 
      finishedText = finishedText.Replace('4', 'd'); 
      finishedText = finishedText.Replace('5', 'e'); 
      finishedText = finishedText.Replace('6', 'f'); 
      finishedText = finishedText.Replace('7', 'g'); 
      finishedText = finishedText.Replace('8', 'h'); 
      finishedText = finishedText.Replace('9', 'i'); 
      finishedText = finishedText.Replace('0', 'j'); 

      return finishedText; 
     } 

     public string convertBackToPrint(string oldText) 
     { 
      string newText = oldText.Replace(",", ""); 
      newText = newText.Replace("#", ""); 
      newText = newText.Replace("*", "å"); 
      newText = newText.Replace(">", "ä"); 
      newText = newText.Replace("[", "ö"); 
      newText = newText.Replace('\'', '.'); 
      newText = newText.Replace('1', ','); 
      newText = newText.Replace('5', '?'); 
      newText = newText.Replace('6', '!'); 
      newText = newText.Replace('3', ':'); 
      newText = newText.Replace('7', '='); 
      newText = newText.Replace('4', '+'); 
      newText = newText.Replace('9', '*'); 
      newText = newText.Replace('=', 'é'); 

      return newText; 
     } 
    } 
} 
+0

podría pegar el código de ejemplo? y también un ejemplo con declaración completa no palabra única. – VIRA

+4

Disculpe mi ignorancia pero, ¿no está el Braille formado por puntos elevados en el papel? – Jodrell

+0

Tal vez deberías usar algo más en lugar de comas: una secuencia de símbolos, que rara vez se encuentran en el texto: Jonas => @ #%^jonas. De lo que podría hacer operaciones inversas más fáciles – horgh

Respuesta

1

Pensando en esto, tal vez, lo que realmente quiere hacer es poner en práctica su propia codificación, llamado algo como PrintableSwedishBrailleAsciiEncoding que hereda de la clase Encoding base.

using System.Text; 

public sealed PrintableSwedishBrailleAsciiEncoding : Encoding 
{ 
    ... 
} 

que maximizaría la resuability de código y que le permitirá utilizar simplemente el resto del marco para hacer su trabajo.


En respuesta a su comentario en mi respuesta ahora eliminado, creo que usted está pidiendo,

¿Cómo puedo reemplazar un cierto carácter, seguido de cualquier número de caracteres no espacios en blanco, hasta el primer espacio en blanco ¿O, de manera más general, palabras enteras que comienzan con un cierto carácter?

lo que podría utilizar un Regex algo como esto, creo que esto se correspondería con un # seguido de un número de caracteres que no sean espacios en blanco.

var numberMatcher = new Regex(@"#\w+") 
var firstMatch = numberMatcher.Match(yourText) 

var alteredMatch = SomeTextAlteringFunction(firstMatch); 

var yourNewText = numberMatcher.Replace(yourText, alteredMatch); 
+0

Sí, eso será perfecto cuando llegue a ese nivel de programación :) Sé que puedo hacer mucho para mejorar mi ConvertingClass, y lo haré más tarde. Pero ahora necesito arreglar esto rápidamente. Mi clase de conversión está funcionando bien, y puedo imprimir sin ningún problema. Mi problema es devolver el texto a su estadística original. –

+0

Sí, eso es correcto. porque cambio cada número a letras con # delante de él. ex 2012 cambiará a #bjab. Y luego quiero convertirlo a números. –

+1

@ JonasLöfkvist, creo que he respondido tu pregunta específica, pero en mi edición pero, si implementaras 'Codificación' correctamente, te permitiría convertir entre 'Unicode' y tu codificación especializada. – Jodrell

0

Esta fue mi solución (Muchas gracias Jodrell)

 public string convertBackToPrint(string oldText) 
     { 
      string newText = oldText.Replace(",", ""); 
      newText = newText.Replace("*", "å"); 
      newText = newText.Replace(">", "ä"); 
      newText = newText.Replace("[", "ö"); 
      newText = newText.Replace('\'', '.'); 
      newText = newText.Replace('1', ','); 
      newText = newText.Replace('5', '?'); 
      newText = newText.Replace('6', '!'); 
      newText = newText.Replace('3', ':'); 
      newText = newText.Replace('7', '='); 
      newText = newText.Replace('4', '+'); 
      newText = newText.Replace('9', '*'); 
      newText = newText.Replace('=', 'é'); 

      var numberMatcher = new Regex(@"#\w+"); 
      var firstMatch = numberMatcher.Match(newText); 
      string alteredMatch = convertToNum(firstMatch.ToString()); 
      string yourNewText = numberMatcher.Replace(newText, alteredMatch); 

      return yourNewText; 
     } 

     private string convertToNum(string oldText) 
     { 
      string newText = ""; 

      newText = oldText.Replace("a", "1"); 
      newText = newText.Replace("b", "2"); 
      newText = newText.Replace("c", "3"); 
      newText = newText.Replace("d", "4"); 
      newText = newText.Replace("e", "5"); 
      newText = newText.Replace("f", "6"); 
      newText = newText.Replace("g", "7"); 
      newText = newText.Replace("h", "8"); 
      newText = newText.Replace("i", "9"); 
      newText = newText.Replace("j", "0"); 
      newText = newText.Replace("#", ""); 

      return newText; 
     }