VB .NET - Strings mit Google uebersetzen

Das ganze habe ich aus dem Internet von Piyush Sha's Blog und noch etwas abgeändert, da der Code bei mir in der Praxis leider nicht funktioniert hat.

Erst die Sprach-Kürzel als Enum:

Public Enum eLocales
  ar
  bg
  hr
  cs
  da
  nl
  en
  fi
  fr
  de
  l
  hi
  ja
  ko
  no
  pl
  pt
  ro
  ru
  es
  sv
End Enum

Und hier die eigentliche Funktion die für die Übersetzung zuständig ist:

''' <summary>
  ''' Translates a text using the Google-API
  ''' </summary>
  ''' <param name="TextToTranslate"></param>
  ''' <param name="lngInput">Input Language</param>
  ''' <param name="lngOutput">Output Language</param>
  ''' <returns>The translated text</returns>
  ''' <remarks></remarks>
  Public Function TranslateText(ByVal TextToTranslate As String, ByVal lngInput As String, ByVal lngOutput As String) As String
    Dim result As String
 
    Try
      Dim url As String = [String].Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}|{2}", TextToTranslate, lngInput, lngOutput)
      Dim webClient As New Net.WebClient()
      webClient.Encoding = System.Text.Encoding.Default
 
      result = webClient.DownloadString(url)
 
      Dim match As String = "id=result_box"
      Dim i As Integer = result.IndexOf(match) + 20
      Dim f As Integer = result.IndexOf(match) + 500
 
      result = Mid(result, i, f)
      result = Mid(result, result.IndexOf(">") + 2, Len(result))
      result = Mid(result, 1, result.IndexOf("</div>"))
 
      result = MakeHTMLValid(result)
    Catch ex As Exception
      result = String.Empty
    End Try
 
    Return result
 
  End Function

Update vom 28.02.2009:

Hier noch die kleine Hilfsfunktion um HTML-Zeichen einigermaßen valide zu machen. Ich weiß, dass das keine wirklich professionelle Lösung ist, daher habe ich den Code ursprünglich auch nicht gepostet. Da aber Nachfragen kamen, anbei als Ergänzung:

''' <summary>
  ''' Format HTML Code a bit
  ''' </summary>
  ''' <param name="aString">The text to format</param>
  ''' <returns></returns>
  ''' <remarks></remarks>
  Public Shared Function MakeHTMLValid(ByVal aString As String) As String
 
    Dim result As String = aString
 
    ' Replace Entities
    result = result.Replace("Ö", "Ö")
    result = result.Replace("ö", "ö")
    result = result.Replace("Ä", "Ä")
    result = result.Replace("ä", "ä")
    result = result.Replace("Ü", "Ü")
    result = result.Replace("ü", "ü")
    result = result.Replace("ß", "ß")
 
    result = result.Replace("€", "€")
 
    Return result
 
  End Function

0 Antworten zu VB .NET - Strings mit Google uebersetzen

  1. Bisher gibt es keine Kommentare.