AppleScript谷歌翻译脚本单词正常但多词选中文本失效问题求助
修复你的谷歌翻译AppleScript多单词问题
我来帮你搞定这个问题!你猜的没错,问题确实出在空格上——你现在用的quoted form of phrase是给Shell命令加引号用的,但谷歌翻译的URL需要的是URL编码后的文本,空格得转换成%20(或者加号),而不是带引号的字符串,这就是多单词时失效的原因。
修复方案
我们需要把选中的文本做URL编码,替换掉原来的引号处理逻辑。AppleScript本身没有内置的URL编码工具,不过可以借助Python的urllib.parse.quote来实现,这是最方便的方式。
修改后的完整脚本
on run {input, parameters} set phrase to input as string -- 使用Python对文本进行URL编码 set encodedPhrase to do shell script "python3 -c 'import urllib.parse; print(urllib.parse.quote(\"" & 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=" & encodedPhrase end run
关键说明
- 替换了原来的
quoted form of phrase,改用Python的URL编码方法,它会自动把空格、特殊字符转换成谷歌翻译能识别的格式(比如空格变成%20)。 - 不管是单个单词还是带空格的长句子,现在生成的URL都能正常被谷歌翻译解析了。
内容的提问来源于stack exchange,提问作者se ba
相关产品推荐
相关产品推荐

