在 iOS 上使用 ML Kit 辨識文字語言

您可以使用 ML Kit 辨識文字字串的語言。你可以 取得字串最可能的語言以及所有相關字詞的可信度分數 字串的可能語言。

ML Kit 可透過原生指令碼辨識超過 100 種語言的文字。 另外,阿拉伯文、保加利亞文、中文、 希臘文、北印度文、日文和俄文。詳情請參閱 支援的語言和指令碼完整清單

立即試用

事前準備

  1. 在 Podfile 中加入下列 ML Kit Pod:
    pod 'GoogleMLKit/LanguageID', '3.2.0'
    
  2. 安裝或更新專案的 Pod 後,請使用 .xcworkspace。Xcode 12.4 以上版本支援 ML Kit。

辨別字串的語言

如要識別字串語言,請取得 LanguageIdentification,然後將字串傳遞至 identifyLanguage(for:) 方法。

例如:

Swift

let languageId = NaturalLanguage.languageIdentification()

languageId.identifyLanguage(for: text) { (languageCode, error) in
  if let error = error {
    print("Failed with error: \(error)")
    return
  }
  if let languageCode = languageCode, languageCode != "und" {
    print("Identified Language: \(languageCode)")
  } else {
    print("No language was identified")
  }
}

Objective-C

MLKLanguageIdentification *languageId = [MLKLanguageIdentification languageIdentification];

[languageId identifyLanguageForText:text
                         completion:^(NSString * _Nullable languageCode,
                                      NSError * _Nullable error) {
                           if (error != nil) {
                             NSLog(@"Failed with error: %@", error.localizedDescription);
                             return;
                           }
                           if (![languageCode isEqualToString:@"und"] ) {
                             NSLog(@"Identified Language: %@", languageCode);
                           } else {
                             NSLog(@"No language was identified");
                           }
                         }];

如果呼叫成功, BCP-47 語言代碼是 傳遞至完成處理常式,會指出文字的語言。如果答案為「否」 系統就能正確偵測語言,就會傳遞 und (未判定) 程式碼。

根據預設,ML Kit 必須識別出非 und 值,才會傳回非 und 值 信賴價值至少為 0.5 的語言。您可以變更這個門檻 方法是將 LanguageIdentificationOptions 物件傳遞至 languageIdentification(options:):

Swift

let options = LanguageIdentificationOptions(confidenceThreshold: 0.4)
let languageId = NaturalLanguage.languageIdentification(options: options)

Objective-C

MLKLanguageIdentificationOptions *options =
    [[MLKLanguageIdentificationOptions alloc] initWithConfidenceThreshold:0.4];
MLKLanguageIdentification *languageId =
    [MLKLanguageIdentification languageIdentificationWithOptions:options];

取得字串的可能語言

如要針對字串最有可能的語言取得可信度值,請得到 LanguageIdentification 的例項,然後將字串傳遞至 identifyPossibleLanguages(for:) 方法。

例如:

Swift

let languageId = NaturalLanguage.languageIdentification()

languageId.identifyPossibleLanguages(for: text) { (identifiedLanguages, error) in
  if let error = error {
    print("Failed with error: \(error)")
    return
  }
  guard let identifiedLanguages = identifiedLanguages,
    !identifiedLanguages.isEmpty,
    identifiedLanguages[0].languageCode != "und"
  else {
    print("No language was identified")
    return
  }

  print("Identified Languages:\n" +
    identifiedLanguages.map {
      String(format: "(%@, %.2f)", $0.languageCode, $0.confidence)
      }.joined(separator: "\n"))
}

Objective-C

MLKLanguageIdentification *languageId = [MLKLanguageIdentification languageIdentification];

[languageId identifyPossibleLanguagesForText:text
                                  completion:^(NSArray * _Nonnull identifiedLanguages,
                                               NSError * _Nullable error) {
  if (error != nil) {
    NSLog(@"Failed with error: %@", error.localizedDescription);
    return;
  }
  if (identifiedLanguages.count == 1
      && [identifiedLanguages[0].languageCode isEqualToString:@"und"] ) {
    NSLog(@"No language was identified");
    return;
  }
  NSMutableString *outputText = [NSMutableString stringWithFormat:@"Identified Languages:"];
  for (MLKIdentifiedLanguage *language in identifiedLanguages) {
    [outputText appendFormat:@"\n(%@, %.2f)", language.languageCode, language.confidence];
  }
  NSLog(outputText);
}];

如果呼叫成功,系統會將 IdentifiedLanguage 物件清單傳遞至 接續處理常式。您可以取得每個物件中語言的 BCP-47 程式碼 以該語言來說,這是很有信心的字串請注意, 這些值代表整個字串位於指定 語言;ML Kit 無法在單一字串中識別多種語言。

根據預設,ML Kit 只會傳回可信度值至少為 0.01。如要變更這個門檻,請傳送 將 LanguageIdentificationOptions 物件轉換為 languageIdentification(options:)

Swift

let options = LanguageIdentificationOptions(confidenceThreshold: 0.4)
let languageId = NaturalLanguage.languageIdentification(options: options)

Objective-C

MLKLanguageIdentificationOptions *options =
    [[MLKLanguageIdentificationOptions alloc] initWithConfidenceThreshold:0.4];
MLKLanguageIdentification *languageId =
    [MLKLanguageIdentification languageIdentificationWithOptions:options];

如果沒有語言符合這項門檻,清單中就會有一個項目,值為 und