首先import最新的NLP包
import NaturalLanguage
1.Language Identification(语言识别)
在wwdc2018视频的例子中,给出了如下的场景:在聊天应用中一个人说出了一句含有”good night“的话,然后弹出了一个晚安的表情,但当使用”我困了要去睡觉了“的中文时,不能弹出,于是引出了一个语言判别的问题。
let recognizer = NLLanguageRecognizer()
recognizer.processString("困死啦睡觉去啦")
let lang = recognizer.dominantLanguage
let hypotheses = recognizer.languageHypotheses(withMaximum: 2)
print(hypotheses)
print(lang)
结果为
[__C.NLLanguage(_rawValue: zh-Hans): 0.9805831909179688, __C.NLLanguage(_rawValue: zh-Hant): 0.01938585191965103]
Optional(__C.NLLanguage(_rawValue: zh-Hans))
我猜前两个的数字为置信值,后一个表示最占主要部分的语言
2.tokenization(词语切分)
这个功能十分强大,可以将词语切分,且支持中文,直觉上感觉这个可以利用的空间非常大
let text = "你好我是小明,我今年二十二岁了"
let tokenizer = NLTokenizer(unit: .word)
tokenizer.string = text
tokenizer.enumerateTokens(in: text.startIndex..<text.endIndex) {