如何判断AppleScript中输入属于哪种语言?

问题描述 投票:0回答:1

我想在macOS上的Services中添加一个项目,例如:

我在网页上选了一个字,然后在维基百科上搜索它的解释。

如果单词是英语,我想搜索“https://en.wikipedia.org/wiki/”,如果单词是中文,我想搜索“https://zh.wikipedia.org/wiki/”。首先,我需要判断输入的语言。我想在AppleScript中如何做到这一点。谢谢。

applescript automator
1个回答
0
投票

据我所知,确定一段文本的语言不能在香草AppleScript中完成,但可以使用AppleScriptObjC来完成。

虽然你不是那么热衷于这个启示,但是,我包括一个片段,证明它实际上很容易做你想要的:

    to guessLanguage for input
        script
            use framework "Foundation"
            property this : a reference to current application
            property NSLTag : a reference to NSLinguisticTagger of this

            to guessLanguage()
                (NSLTag's dominantLanguageForString:input) as text
            end guessLanguage
        end script

        result's guessLanguage()
    end guessLanguage

您应该在end run之后将此处理程序放在脚本的底部。它可以在脚本中的任何位置调用,如下所示:

    on run {input, parameters}
        set [input] to the input
        guessLanguage for the input
        set lang to text 1 thru 2 of result

        open location "https://" & lang & ".wikipedia.org/wiki/" & input
    end run

    to guessLanguage for input
        .
        .
        .
    end guessLanguage

以下是针对不同语言样本的几个测试运行,显示每个样本旁边的返回结果:

    guessLanguage for "Hello, how are you?" --> "en"
    guessLanguage for "Guten Tag, wie gehts?" --> "de"
    guessLanguage for "Salut, ça va?" --> "fr" 
    guessLanguage for "你好!你好嗎?" --> "zh-Hant"
    guessLanguage for "こんにちは、元気ですか?" --> "ja"
© www.soinside.com 2019 - 2024. All rights reserved.