Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Pour analyser un extrait de texte et en extraire les entités, appelez l'API d'extraction d'entités ML Kit en transmettant le texte directement à sa méthode annotateText:completion:. Vous pouvez également transmettre un objet EntityExtractionParams facultatif contenant d'autres options de configuration, telles qu'une heure de référence, un fuseau horaire ou un filtre pour limiter la recherche à un sous-ensemble de types d'entités.
L'API renvoie une liste d'objets EntityAnnotation contenant des informations sur chaque entité.
Les éléments du détecteur de base d'extraction d'entités sont liés de manière statique au moment de l'exécution de l'application.
Ils ajoutent environ 10,7 Mo à votre application.
Essayer
Testez l'application exemple pour voir un exemple d'utilisation de cette API.
Avant de commencer
Incluez les bibliothèques ML Kit suivantes dans votre Podfile:
pod 'GoogleMLKit/EntityExtraction', '8.0.0'
Après avoir installé ou mis à jour les pods de votre projet, ouvrez votre projet Xcode à l'aide de son fichier .xcworkspace. ML Kit est compatible avec Xcode 13.2.1 ou version ultérieure.
Extraire des entités à partir d'un texte
Pour extraire des entités à partir d'un texte, créez d'abord un objet EntityExtractorOptions en spécifiant la langue, puis utilisez-le pour instancier un EntityExtractor:
Swift
// Note: You can specify any of the 15 languages entity extraction supports here. letoptions=EntityExtractorOptions(modelIdentifier:EntityExtractionModelIdentifier.english)letentityExtractor=EntityExtractor.entityExtractor(options:options)
Objective-C
// Note: You can specify any of the 15 languages entity extraction supports here. MLKEntityExtractorOptions*options=[[MLKEntityExtractorOptionsalloc]initWithModelIdentifier:MLKEntityExtractionModelIdentifierEnglish];MLKEntityExtractor*entityExtractor=[MLKEntityExtractorentityExtractorWithOptions:options];
Assurez-vous ensuite que le modèle de langage requis est téléchargé sur l'appareil:
Swift
entityExtractor.downloadModelIfNeeded(completion:{// If the error is nil, the download completed successfully.})
Objective-C
[entityExtractordownloadModelIfNeededWithCompletion:^(NSError*_Nullableerror){// If the error is nil, the download completed successfully.}];
Une fois le modèle téléchargé, transmettez une chaîne et un MLKEntityExtractionParams facultatif à la méthode annotate.
Swift
// The EntityExtractionParams parameter is optional. Only instantiate and// configure one if you need to customize one or more of its params.varparams=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,errorin// 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=[[MLKEntityExtractionParamsalloc]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=[NSDatedate];params.referenceTimeZone=[NSTimeZonetimeZoneWithAbbreviation:@"GMT"];params.preferredLocale=[NSLocalelocalWithLocaleIdentifier:@"en-US"];params.typesFilter=[NSSetsetWithObjects:MLKEntityExtractionEntityTypeAddress,MLKEntityExtractionEntityTypeDateTime,nil];[extractorannotateText:text.stringwithParams:paramscompletion:^(NSArray*_Nullableresult,NSError*_Nullableerror){// If the error is nil, the annotation completed successfully and any results // will be contained in the `result` array.}
Itérer sur les résultats d'annotation pour récupérer des informations sur les entités reconnues.
Swift
// let annotations be the Array! returned from EntityExtractorforannotationinannotations{letentities=annotation.entitiesforentityinentities{switchentity.entityType{caseEntityType.dateTime:guardletdateTimeEntity=entity.dateTimeEntityelse{print("This field should be populated.")return}print("Granularity: %d",dateTimeEntity.dateTimeGranularity)print("DateTime: %@",dateTimeEntity.dateTime)caseEntityType.flightNumber:guardletflightNumberEntity=entity.flightNumberEntityelse{print("This field should be populated.")return}print("Airline Code: %@",flightNumberEntity.airlineCode)print("Flight number: %@",flightNumberEntity.flightNumber)caseEntityType.money:guardletmoneyEntity=entity.moneyEntityelse{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 EntityExtractorfor(MLKEntityAnnotation*annotationinannotations){NSArray*entities=annotation.entities;NSLog(@"Range: [%d, %d)",(int)annotation.range.location,(int)(annotation.range.location+annotation.range.length));for(MLKEntity*entityinentities){if([entity.entityTypeisEqualToString:MLKEntityExtractionEntityTypeDateTime]){MLKDateTimeEntity*dateTimeEntity=entity.dateTimeEntity;NSLog(@"Granularity: %d",(int)dateTimeEntity.dateTimeGranularity);NSLog(@"DateTime: %@",dateTimeEntity.dateTime);break;}elseif([entity.entityTypeisEqualToString:MLKEntityExtractionEntityTypeFlightNumber]){MLKFlightNumberEntity*flightNumberEntity=entity.flightNumberEntity;NSLog(@"Airline Code: %@",flightNumberEntity.airlineCode);NSLog(@"Flight number: %@",flightNumberEntity.flightNumber);break;}elseif([entity.entityTypeisEqualToString: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);}}
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/08/29 (UTC).
[null,null,["Dernière mise à jour le 2025/08/29 (UTC)."],[[["\u003cp\u003eThis is a beta API for extracting entities (like dates, addresses, flight numbers) from text using machine learning.\u003c/p\u003e\n"],["\u003cp\u003eThe API requires adding the \u003ccode\u003eGoogleMLKit/EntityExtraction\u003c/code\u003e pod and downloading language models before use.\u003c/p\u003e\n"],["\u003cp\u003eYou can customize the entity extraction process by specifying language, time zone, and filtering for specific entity types.\u003c/p\u003e\n"],["\u003cp\u003eThe API returns an array of \u003ccode\u003eEntityAnnotation\u003c/code\u003e objects containing information about each identified entity in the text.\u003c/p\u003e\n"],["\u003cp\u003eThis API has a 10.7MB footprint and is only compatible with 64-bit devices running iOS.\u003c/p\u003e\n"]]],["The ML Kit entity extraction API analyzes text to identify entities. To use it, include the `GoogleMLKit/EntityExtraction` library, create `EntityExtractorOptions`, and instantiate an `EntityExtractor`. Download the required language model and then use the `annotateText` method, optionally with `EntityExtractionParams` for customization. The API returns a list of `EntityAnnotation` objects. The API is in beta and adds 10.7MB to your app.\n"],null,["| This API is offered in beta, and is not subject to any SLA or deprecation policy. Changes may be made to this API that break backward compatibility.\n\nTo analyze a piece of text and extract the\nentities in it, invoke the ML Kit entity extraction API by passing\nthe text directly to its `annotateText:completion:` method. It is also possible to\npass in an optional `EntityExtractionParams` object which contains other\nconfiguration options such as a reference time, timezone, or\na filter to limit the search for a subset of entity types.\nThe API returns a list of `EntityAnnotation` objects containing information about each entity.\n\nThe entity extraction base detector assets are statically linked at app run time.\nThey add about 10.7MB to your app.\n| **Note:** ML Kit iOS APIs only run on 64-bit devices. If you build your app with 32-bit support, check the device's architecture before using this API.\n\nTry it out\n\n- Play around with [the sample app](https://github.com/googlesamples/mlkit/tree/master/ios/quickstarts/entityextraction) to see an example usage of this API.\n\nBefore you begin\n\n1. Include the following ML Kit libraries in your Podfile:\n\n pod 'GoogleMLKit/EntityExtraction', '8.0.0'\n\n2. After you install or update your project's Pods, open your Xcode project using its .xcworkspace. ML Kit is supported in Xcode version 13.2.1 or higher.\n\nExtract entities from text\n\nTo extract entities from text, first create an `EntityExtractorOptions` object by specifying the language and use that to instantiate an `EntityExtractor`: \n\nSwift \n\n```swift\n// Note: You can specify any of the 15 languages entity extraction supports here. \nlet options = EntityExtractorOptions(modelIdentifier: \n EntityExtractionModelIdentifier.english)\nlet entityExtractor = EntityExtractor.entityExtractor(options: options)\n```\n\nObjective-C \n\n```objective-c\n// Note: You can specify any of the 15 languages entity extraction supports here. \nMLKEntityExtractorOptions *options = \n [[MLKEntityExtractorOptions alloc] \n initWithModelIdentifier:MLKEntityExtractionModelIdentifierEnglish];\n\nMLKEntityExtractor *entityExtractor = \n [MLKEntityExtractor entityExtractorWithOptions:options];\n```\n\nNext, ensure that the required language model is downloaded to the device: \n\nSwift \n\n```swift\nentityExtractor.downloadModelIfNeeded(completion: {\n // If the error is nil, the download completed successfully.\n})\n```\n\nObjective-C \n\n```objective-c\n[entityExtractor downloadModelIfNeededWithCompletion:^(NSError *_Nullable error) {\n // If the error is nil, the download completed successfully.\n}];\n```\n\nOnce the model has been downloaded, pass a string and an optional\n`MLKEntityExtractionParams` to the `annotate` method. \n\nSwift \n\n```swift\n// The EntityExtractionParams parameter is optional. Only instantiate and\n// configure one if you need to customize one or more of its params.\nvar params = EntityExtractionParams()\n// The params object contains the following properties which can be customized on\n// each annotateText: call. Please see the class's documentation for a more\n// detailed description of what each property represents.\nparams.referenceTime = Date();\nparams.referenceTimeZone = TimeZone(identifier: \"GMT\");\nparams.preferredLocale = Locale(identifier: \"en-US\");\nparams.typesFilter = Set([EntityType.address, EntityType.dateTime])\n\nextractor.annotateText(\n text.string,\n params: params,\n completion: {\n result, error in\n // If the error is nil, the annotation completed successfully and any results \n // will be contained in the `result` array.\n }\n)\n```\n\nObjective-C \n\n```objective-c\n// The MLKEntityExtractionParams property is optional. Only instantiate and\n// configure one if you need to customize one or more of its params.\nMLKEntityExtractionParams *params = [[MLKEntityExtractionParams alloc] init];\n// The params object contains the following properties which can be customized on\n// each annotateText: call. Please see the class's documentation for a fuller \n// description of what each property represents.\nparams.referenceTime = [NSDate date];\nparams.referenceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@\"GMT\"];\nparams.preferredLocale = [NSLocale localWithLocaleIdentifier:@\"en-US\"];\nparams.typesFilter = \n [NSSet setWithObjects:MLKEntityExtractionEntityTypeAddress, \n MLKEntityExtractionEntityTypeDateTime, nil];\n\n[extractor annotateText:text.string\n withParams:params\n completion:^(NSArray *_Nullable result, NSError *_Nullable error) {\n // If the error is nil, the annotation completed successfully and any results \n // will be contained in the `result` array.\n}\n```\n\nLoop over the annotation results to retrieve information about the\nrecognized entities. \n\nSwift \n\n```swift\n// let annotations be the Array! returned from EntityExtractor\nfor annotation in annotations {\n let entities = annotation.entities\n for entity in entities {\n switch entity.entityType {\n case EntityType.dateTime:\n guard let dateTimeEntity = entity.dateTimeEntity else {\n print(\"This field should be populated.\")\n return\n }\n print(\"Granularity: %d\", dateTimeEntity.dateTimeGranularity)\n print(\"DateTime: %@\", dateTimeEntity.dateTime)\n case EntityType.flightNumber:\n guard let flightNumberEntity = entity.flightNumberEntity else {\n print(\"This field should be populated.\")\n return\n }\n print(\"Airline Code: %@\", flightNumberEntity.airlineCode)\n print(\"Flight number: %@\", flightNumberEntity.flightNumber)\n case EntityType.money:\n guard let moneyEntity = entity.moneyEntity else {\n print(\"This field should be populated.\")\n return\n }\n print(\"Currency: %@\", moneyEntity.integerPart)\n print(\"Integer Part: %d\", moneyEntity.integerPart)\n print(\"Fractional Part: %d\", moneyEntity.fractionalPart)\n // Add additional cases as needed.\n default:\n print(\"Entity: %@\", entity);\n }\n }\n}\n```\n\nObjective-C \n\n```objective-c\nNSArray *annotations; // Returned from EntityExtractor\n\nfor (MLKEntityAnnotation *annotation in annotations) {\n NSArray *entities = annotation.entities;\n NSLog(@\"Range: [%d, %d)\", (int)annotation.range.location, (int)(annotation.range.location + annotation.range.length));\n for (MLKEntity *entity in entities) {\n if ([entity.entityType isEqualToString:MLKEntityExtractionEntityTypeDateTime]) {\n MLKDateTimeEntity *dateTimeEntity = entity.dateTimeEntity;\n NSLog(@\"Granularity: %d\", (int)dateTimeEntity.dateTimeGranularity);\n NSLog(@\"DateTime: %@\", dateTimeEntity.dateTime);\n break;\n } else if ([entity.entityType isEqualToString:MLKEntityExtractionEntityTypeFlightNumber]) {\n MLKFlightNumberEntity *flightNumberEntity = entity.flightNumberEntity;\n NSLog(@\"Airline Code: %@\", flightNumberEntity.airlineCode);\n NSLog(@\"Flight number: %@\", flightNumberEntity.flightNumber);\n break;\n } else if ([entity.entityType isEqualToString:MLKEntityExtractionEntityTypeMoney]) {\n MLKMoneyEntity *moneyEntity = entity.moneyEntity;\n NSLog(@\"Currency: %@\", moneyEntity.unnormalizedCurrency);\n NSLog(@\"Integer Part: %d\", (int)moneyEntity.integerPart);\n NSLog(@\"Fractional Part: %d\", (int)moneyEntity.fractionalPart);\n break;\n } else {\n // Add additional cases as needed.\n NSLog(@\"Entity: %@\", entity);\n }\n }\n```"]]