在 iOS 上使用 ML Kit 擷取實體

如要分析一段文字並擷取其中的實體,請將文字直接傳送至其 annotateText:completion: 方法以叫用 ML Kit 實體擷取 API。系統也可以傳入包含其他設定選項的選用 EntityExtractionParams 物件,例如參考時間、時區或篩選器,藉此限制搜尋部分實體類型。API 會傳回 EntityAnnotation 物件清單,其中包含每個實體的相關資訊。

實體擷取基礎偵測工具資產會在應用程式執行期間以靜態方式連結。而這會增加約 10.7 MB 到您的應用程式。

立即體驗

事前準備

  1. 在 Podfile 中加入下列 ML Kit 程式庫:

    pod 'GoogleMLKit/EntityExtraction', '3.2.0'
    
  2. 安裝或更新專案的 Pod 後,請使用相應的 .xcworkspace 開啟 Xcode 專案。ML Kit 支援 Xcode 13.2.1 以上版本。

從文字中擷取實體

如要從文字中擷取實體,請先指定語言來建立 EntityExtractorOptions 物件,然後使用該物件對 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];

接著,請確認所需語言模型已下載到裝置上:

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.
}];

下載模型後,請將字串和選用的 MLKEntityExtractionParams 傳遞至 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.
}

循環處理註解結果,以擷取可辨識實體的相關資訊。

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);
              }
            }