TextStructure
is a very nice new function in Mathematica. It can create amazing things like:
TextStructure@"If love be blind, love cannot hit the mark."
Can we do the same for translations?
This piece of code downloads a JSON-like code from google translate without the need for API calls (which I never bothered to learn).
GoogleTranslate[str_String] := GoogleTranslate@str = Import[
StringTemplate["https://translate.googleapis.com/translate_a/single?client=gtx&sl=`1`&tl=`2`&dt=t&q=`3`"][
"pt", "en", URLEncode@str], "JSON"][[1, 1, 1]]
And this other piece of code formats the translation.
MakeBoxes[TranslateElement[main_, down_], _] := GridBox[
{{MakeBoxes@main}, {StyleBox[MakeBoxes@down, "TextElementLabel"]}},
BaseStyle -> "TextElementGrid"]
GoogleTranslateStructure[str_String] := Block[{sentence, words, phrase},
sentence = StringSplit[str, p:"."|"," :> p] //. {a___String, s_String, p:"."|",", b___String} :> {a, s<>p, b};
phrase = Table[
words = StringSplit[sentence[[i]], WhitespaceCharacter];
TranslateElement[Row@Riffle[TranslateElement @@@ Transpose@{words, GoogleTranslate /@ words}, " "], GoogleTranslate@sentence[[i]]]
, {i, Length@sentence}];
If[Length@sentence == 1,
phrase[[1]],
TranslateElement[Row@Riffle[phrase, " "], GoogleTranslate@str]
]
]
A usage example would be:
GoogleTranslateStructure@"Se amor é cego, nunca acerta o alvo."
Changing the language from English to Japanese (which I don't speak, btw):
Or French: