Home > Net >  Applescript Google Translate
Applescript Google Translate

Time:10-19

The code works fine when the selected text is just one word but for more than one word it doesn't. I think spaces between words cause this problem yet I have no idea how to fix it.

on run {input, parameters}
 set phrase to input as string
 set phrase to quoted form of phrase

 set ui_lang to "en"
 set from_lang to "en"
 set to_lang to "tr"

 return "https://translate.google.com/?hl=" & ui_lang & "&sl=" & from_lang & "&tl=" & to_lang & "&text=" & phrase

end run

CodePudding user response:

If it's to form part of the URL, then using quoted form will not work, as that prepares text intended for the shell.

For a web address, special characters, including the space, must be url encoded. Spaces are replaced with and other special character have their own '%' code.

A quick and dirty method to solve this specific case involves replacing the spaces with ' ' by having these as your first three lines:

set phrase to input as string -- no changes
set AppleScript's text item delimiters to {" "}
set phrase to words of phrase as text

Basically, it breaks your string into words and rejoins them with instead of spaces. It should work with a single word input as well. You should change the TID back to whatever (or the default {""}) in a subsequent line.

For example:

"and empathetic programmers" becomes "and empathetic programmers" which becomes "https://translate.google/?hl=en&sl=en&tl=tr&text=and empathetic programmers"

There are numerous questions on this site that discuss the subject, including some that are applescript-specific. You can also find more, including some handlers here: Text Encoding | Decoding and Encoding and Decoding Text

There is a lot written on this subject so it's an easy search. There are numerous online encoder/decoders as well, which you can use for testing comparisons.

CodePudding user response:

on run {input, parameters}
    
    set phrase to input as string
    
    set ui_lang to "en"
    set from_lang to "en"
    set to_lang to "tr"
    
    open location "https://translate.google.com/?hl=" & ui_lang & "&sl=" & from_lang & "&tl=" & to_lang & "&text=" & phrase
    
end run
  • Related