使用NLLanguageRecognizer识别文本中的语言
参考自苹果官方文档
使用语言识别器检测一段文本中的语言。
import NaturalLanguage
// 创建检测器
let recognizer = NLLanguageRecognizer()
recognizer.processString("This is a test, mein Freund. ")
//
if let language = recognizer.dominantLanguage {
print(language.rawValue) // en
} else {
print("Language not recognized")
}
// Generate up to two language hypotheses. 生成最多两种语言假设
let hypotheses = recognizer.languageHypotheses(withMaximum: 2)
print(hypotheses) // [__C.NLLanguage(_rawValue: de): 0.43922990560531616, __C.NLLanguage(_rawValue: en): 0.5024932026863098]
// Specify constraints for language identification. 为语言识别指定约束。
recognizer.languageConstraints = [.french, .english, .german,
.italian, .spanish, .portuguese]
// 限制语言的概率
recognizer.languageHints = [.french: 0.5,
.english: 0.9,
.german: 0.8,
.italian: 0.6,
.spanish: 0.3,
.portuguese: 0.2]
let constrainedHypotheses = recognizer.languageHypotheses(withMaximum: 2)
print(constrainedHypotheses)
// Reset the recognizer to its initial state. 重置(如果需要继续识别的话)
recognizer.reset()
// Process additional strings for language identification.
recognizer.processString("Este es un idioma diferente.")
输入内容为
en
[__C.NLLanguage(_rawValue: en): 0.5024932026863098, __C.NLLanguage(_rawValue: de): 0.43922990560531616]
[__C.NLLanguage(_rawValue: de): 0.43683740496635437, __C.NLLanguage(_rawValue: en): 0.5622255802154541]