Para analizar un texto y extraer el
en él, invoca la API de extracción de entidades del ML Kit pasando
el texto directamente a su método annotateText:completion:
. También es posible
pasa un objeto EntityExtractionParams
opcional que contiene otros
opciones de configuración como una hora de referencia, una zona horaria o
un filtro para limitar la búsqueda de un subconjunto de tipos de entidades.
La API muestra una lista de objetos EntityAnnotation
que contienen información sobre cada entidad.
Los recursos del detector base de extracción de entidades se vinculan de forma estática en el entorno de ejecución de la app. Agregan alrededor de 10.7 MB a tu app.
Probar
- Prueba la app de ejemplo para ver un ejemplo de uso de esta API.
Antes de comenzar
Incluye las siguientes bibliotecas de ML Kit en tu Podfile:
pod 'GoogleMLKit/EntityExtraction', '3.2.0'
Después de instalar o actualizar los Pods de tu proyecto, abre el proyecto de Xcode a través de su archivo .xcworkspace. El Kit de AA es compatible con Xcode 13.2.1 o versiones posteriores.
Extrae entidades del texto
Si quieres extraer entidades de un texto, primero especifica el idioma para crear un objeto EntityExtractorOptions
y úsalo para crear una instancia de EntityExtractor
:
Swift
// Note: You can specify any of the 15 languages entity extraction supports here. let options = EntityExtractorOptions(modelIdentifier: EntityExtractionModelIdentifier.english) let entityExtractor = EntityExtractor.entityExtractor(options: options)
Objective-C
// Note: You can specify any of the 15 languages entity extraction supports here. MLKEntityExtractorOptions *options = [[MLKEntityExtractorOptions alloc] initWithModelIdentifier:MLKEntityExtractionModelIdentifierEnglish]; MLKEntityExtractor *entityExtractor = [MLKEntityExtractor entityExtractorWithOptions:options];
Luego, asegúrate de que el modelo de idioma requerido se haya descargado en el dispositivo:
Swift
entityExtractor.downloadModelIfNeeded(completion: { // If the error is nil, the download completed successfully. })
Objective-C
[entityExtractor downloadModelIfNeededWithCompletion:^(NSError *_Nullable error) { // If the error is nil, the download completed successfully. }];
Una vez que el modelo se haya descargado, pasa una cadena y un
MLKEntityExtractionParams
al método annotate
Swift
// The EntityExtractionParams parameter is optional. Only instantiate and // configure one if you need to customize one or more of its params. var params = EntityExtractionParams() // The params object contains the following properties which can be customized on // each annotateText: call. Please see the class's documentation for a more // detailed description of what each property represents. params.referenceTime = Date(); params.referenceTimeZone = TimeZone(identifier: "GMT"); params.preferredLocale = Locale(identifier: "en-US"); params.typesFilter = Set([EntityType.address, EntityType.dateTime]) extractor.annotateText( text.string, params: params, completion: { result, error in // If the error is nil, the annotation completed successfully and any results // will be contained in the `result` array. } )
Objective-C
// The MLKEntityExtractionParams property is optional. Only instantiate and // configure one if you need to customize one or more of its params. MLKEntityExtractionParams *params = [[MLKEntityExtractionParams alloc] init]; // The params object contains the following properties which can be customized on // each annotateText: call. Please see the class's documentation for a fuller // description of what each property represents. params.referenceTime = [NSDate date]; params.referenceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; params.preferredLocale = [NSLocale localWithLocaleIdentifier:@"en-US"]; params.typesFilter = [NSSet setWithObjects:MLKEntityExtractionEntityTypeAddress, MLKEntityExtractionEntityTypeDateTime, nil]; [extractor annotateText:text.string withParams:params completion:^(NSArray*_Nullable result, NSError *_Nullable error) { // If the error is nil, the annotation completed successfully and any results // will be contained in the `result` array. }
Repite los resultados de la anotación para recuperar información sobre la reconocidas.
Swift
// let annotations be the Array! returned from EntityExtractor for annotation in annotations { let entities = annotation.entities for entity in entities { switch entity.entityType { case EntityType.dateTime: guard let dateTimeEntity = entity.dateTimeEntity else { print("This field should be populated.") return } print("Granularity: %d", dateTimeEntity.dateTimeGranularity) print("DateTime: %@", dateTimeEntity.dateTime) case EntityType.flightNumber: guard let flightNumberEntity = entity.flightNumberEntity else { print("This field should be populated.") return } print("Airline Code: %@", flightNumberEntity.airlineCode) print("Flight number: %@", flightNumberEntity.flightNumber) case EntityType.money: guard let moneyEntity = entity.moneyEntity else { print("This field should be populated.") return } print("Currency: %@", moneyEntity.integerPart) print("Integer Part: %d", moneyEntity.integerPart) print("Fractional Part: %d", moneyEntity.fractionalPart) // Add additional cases as needed. default: print("Entity: %@", entity); } } }
Objective-C
NSArray*annotations; // Returned from EntityExtractor for (MLKEntityAnnotation *annotation in annotations) { NSArray *entities = annotation.entities; NSLog(@"Range: [%d, %d)", (int)annotation.range.location, (int)(annotation.range.location + annotation.range.length)); for (MLKEntity *entity in entities) { if ([entity.entityType isEqualToString:MLKEntityExtractionEntityTypeDateTime]) { MLKDateTimeEntity *dateTimeEntity = entity.dateTimeEntity; NSLog(@"Granularity: %d", (int)dateTimeEntity.dateTimeGranularity); NSLog(@"DateTime: %@", dateTimeEntity.dateTime); break; } else if ([entity.entityType isEqualToString:MLKEntityExtractionEntityTypeFlightNumber]) { MLKFlightNumberEntity *flightNumberEntity = entity.flightNumberEntity; NSLog(@"Airline Code: %@", flightNumberEntity.airlineCode); NSLog(@"Flight number: %@", flightNumberEntity.flightNumber); break; } else if ([entity.entityType isEqualToString:MLKEntityExtractionEntityTypeMoney]) { MLKMoneyEntity *moneyEntity = entity.moneyEntity; NSLog(@"Currency: %@", moneyEntity.unnormalizedCurrency); NSLog(@"Integer Part: %d", (int)moneyEntity.integerPart); NSLog(@"Fractional Part: %d", (int)moneyEntity.fractionalPart); break; } else { // Add additional cases as needed. NSLog(@"Entity: %@", entity); } }