Puedes usar ML Kit para identificar el idioma de una string de texto. Puedes obtener el idioma más probable de la string, así como las puntuaciones de confianza de todos sus posibles idiomas.
El ML Kit reconoce texto en más de 100 idiomas en sus alfabetos nativos. Además, puede reconocer texto latinizado en idiomas como el árabe, búlgaro, chino, griego, hindi, japonés y ruso. Consulta la lista completa de lenguajes y secuencias de comandos compatibles.
Probar
- Prueba la app de ejemplo para ver un ejemplo de uso de esta API.
Antes de comenzar
- Incluye los siguientes pods del ML Kit en tu Podfile:
pod 'GoogleMLKit/LanguageID', '3.2.0'
- Después de instalar o actualizar los Pods de tu proyecto, abre el proyecto de Xcode con su
.xcworkspace
. El ML Kit es compatible con Xcode 12.4 o versiones posteriores.
Identifica el idioma de una cadena
Para identificar el idioma de una string, obtén una instancia de LanguageIdentification
y, luego, pasa la string al método identifyLanguage(for:)
.
Por ejemplo:
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"); } }];
Si la llamada se ejecuta correctamente, se pasa un código de idioma BCP-47 al controlador de finalización, el cual indica el idioma del texto. Si no se pudo detectar un idioma con confianza, se pasa el código und
(indeterminado).
Según la configuración predeterminada, el ML Kit muestra un valor distinto de und
solo cuando identifica el idioma con un valor de confianza de al menos 0.5. Para cambiar este umbral,
pasa un objeto LanguageIdentificationOptions
a
languageIdentification(options:)
de la siguiente manera:
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];
Obtén los posibles idiomas de una string
Para ver los valores de confianza de los idiomas más probables de una string, obtén una instancia de LanguageIdentification
y, luego, pasa la string al método identifyPossibleLanguages(for:)
.
Por ejemplo:
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); }];
Si la llamada se ejecuta correctamente, se pasará una lista de objetos IdentifiedLanguage
al controlador de continuación. Podrás obtener el código BCP-47 del idioma en cada objeto y estar seguro de que la string está en ese idioma. Ten en cuenta que estos valores señalan con seguridad que la string completa está en el idioma determinado. El ML Kit no identifica varios idiomas en una sola string.
Según la configuración predeterminada, el ML Kit solo muestra los idiomas con valores de confianza de al menos 0.01. Para cambiar este umbral, pasa un objeto LanguageIdentificationOptions
a languageIdentification(options:)
de la siguiente manera:
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];
Si ningún idioma alcanza este umbral, la lista tiene un elemento con el valor und
.