加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift如何判断字符串的语言

发布时间:2020-12-14 06:35:34 所属栏目:百科 来源:网络整理
导读:有时我们需要判断一段文字是属于那种语言:英文?韩文?还是中文?虽说这也算某种程度的猜测,但至少比你自己瞎猜要准确地多! ;) 这里提供三种方法. 首先如果你只在MacOS上运行的话,你可以用AppKit中的NSSpellChecker类: import AppKitlet checker = NSSpellCheck

有时我们需要判断一段文字是属于那种语言:英文?韩文?还是中文?虽说这也算某种程度的猜测,但至少比你自己瞎猜要准确地多! ;)

这里提供三种方法.

首先如果你只在MacOS上运行的话,你可以用AppKit中的NSSpellChecker类:

import AppKit

let checker = NSSpellChecker.shared()
checker.automaticallyIdentifiesLanguages = true
let str = "猫猪侯佩,弄啥呢!!!"
checker.requestChecking(of: str,range: NSRange(location: 0,length: str.characters.count),types: NSTextCheckingResult.CheckingType.orthography.rawValue,options: nil,inSpellDocumentWithTag: 0){num,results,orthography,count in
    print("(orthography.dominantLanguage)")
}

最终打印的是:zh-Hans

如果你要在iOS上实现这个功能,那么在UIKit中也有一个对应的类UITextChecker,不过遗憾的是该类貌似只能事先指定语言,而不可以侦测语言.而且该类的强项是对单词做拼写检查,你可以列出其所有支持的语言:

UITextChecker.availableLanguages

返回结果是:

["en_US","en_CA","pt_BR","it_IT","ko_KR","nb_NO","de_DE","en_GB","sv_SE","en_AU","en_SG","es_MX","pt_PT","en_IN","fr_FR","es_ES","nl_NL","tr_TR","fi_FI","pl_PL","ru_RU","da_DK"]

So,如果你的目标是iOS,那么你可以使用下面两种方法.

第一种是比较底层的方法,但代码比较简洁,大多数代码用在底层类到高层类的转换上:

func testLangWith(string:String)->String?{
    if string.characters.count < 100{
 return CFStringTokenizerCopyBestStringLanguage(string as CFString!,CFRange(location: 0,length: string.characters.count)) as String?
    }else{
 return CFStringTokenizerCopyBestStringLanguage(string as CFString!,length: 100)) as String?
    }
}

第二种是使用NSLinguisticTagger这个类,代码如下:

func testLangWith(string:String)->String?{
    let tagSchemes = [NSLinguisticTagSchemeLanguage]
    let tagger = NSLinguisticTagger(tagSchemes: tagSchemes,options: 0)
    tagger.string = string
    let lang = tagger.tag(at: 0,scheme: NSLinguisticTagSchemeLanguage,tokenRange: nil,sentenceRange: nil)
    return lang
}

下面测试一段韩文:

let str = "???? ??? ???. ??? ??? ???? ? ????. ??? ???? ???. ???? ???? ?????. ???? ??? ?? ?? ?? ??? ?????. ???? ??? ?? ?? ??? ?? ? ????."

let lang = testLangWith(string: str)

最终lang值为:”ko”

PS:上面那一段韩文的意思是:

不要只看外貌,它会迷惑你。不要贪恋财产,它们终究是会消失的。请选择能够对你微笑的人吧,微笑能使忧郁的日子变得明朗。

:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读