Trích xuất thực thể bằng Bộ công cụ học máy trên iOS

Để phân tích một đoạn văn bản và trích xuất các thực thể trong văn bản đó, hãy gọi API trích xuất thực thể của Bộ công cụ học máy bằng cách chuyển văn bản đó trực tiếp vào phương thức annotateText:completion:. Bạn cũng có thể truyền vào một đối tượng EntityExtractionParams không bắt buộc chứa các tuỳ chọn cấu hình khác, chẳng hạn như thời gian tham chiếu, múi giờ hoặc bộ lọc để giới hạn hoạt động tìm kiếm một tập hợp con các loại thực thể. API trả về danh sách các đối tượng EntityAnnotation chứa thông tin về từng thực thể.

Các tài sản của trình phát hiện cơ sở trích xuất thực thể được liên kết tĩnh trong thời gian chạy ứng dụng. Chúng thêm khoảng 10,7 MB vào ứng dụng của bạn.

Dùng thử

Trước khi bắt đầu

  1. Đưa các thư viện sau đây của Bộ công cụ học máy vào Podfile:

    pod 'GoogleMLKit/EntityExtraction', '3.2.0'
    
  2. Sau khi bạn cài đặt hoặc cập nhật các Nhóm của dự án, hãy mở dự án Xcode của bạn bằng miền .xcworkspace. Bộ công cụ học máy được hỗ trợ trong Xcode phiên bản 13.2.1 trở lên.

Trích xuất các đối tượng từ văn bản

Để trích xuất các thực thể từ văn bản, trước tiên hãy tạo đối tượng EntityExtractorOptions bằng cách chỉ định ngôn ngữ và sử dụng ngôn ngữ đó để tạo thực thể cho 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];

Tiếp theo, hãy đảm bảo rằng mô hình ngôn ngữ cần thiết đã được tải xuống thiết bị:

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

Sau khi đã tải mô hình xuống, hãy truyền một chuỗi và MLKEntityExtractionParams (không bắt buộc) vào phương thức 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.
}

Lặp lại kết quả chú giải để truy xuất thông tin về các thực thể đã nhận dạng.

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