HarmonyOS鸿蒙Next中textProcessing.getEntity()不执行

HarmonyOS鸿蒙Next中textProcessing.getEntity()不执行 在使用 Natural Language Kit(自然语言理解服务)时, textProcessing.getEntity() 不执行

代码:

import { textProcessing, EntityType } from '@kit.NaturalLanguageKit';

@Entry
@Component
struct Index {
  // 步骤1:需要解析的内容
  private inputText: string = '请联系张三:13800138000';

  build() {
    Column() {

        Button('获取实体结果')
          .type(ButtonType.Capsule)
          .fontColor(Color.White)
          .width('45%')
          .margin(10)
          .onClick(async () => {
            console.log("1=>",textProcessing?.getEntity) // 1 => undefined 这里为什么是undefined?

            // 步骤2:调用实体抽取API
            let result = await textProcessing.getEntity( // undefined.getEntity 这里不执行?
              this.inputText,
              { entityTypes: [EntityType.NAME, EntityType.PHONE_NO] } // 指定抽取姓名和电话
            );

            // 步骤3:解析结果
            result.forEach(entity => {
              console.log(`实体类型: ${entity.type} | 文本: ${entity.text}`);
            });
          })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

更多关于HarmonyOS鸿蒙Next中textProcessing.getEntity()不执行的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS Next中,textProcessing.getEntity()未执行可能由于以下原因:

  1. 未正确导入@kit.ArkTS@ohos.ai.nlu相关模块。
  2. 缺少必要的权限配置,需在module.json5中声明ohos.permission.NLU权限。
  3. 未调用textProcessing.getEntity()前的初始化方法,如createTextProcessing()未成功执行。
  4. 输入文本为空或格式不符合实体识别要求。
  5. SDK版本不兼容,需检查HarmonyOS Next与API版本的匹配性。

更多关于HarmonyOS鸿蒙Next中textProcessing.getEntity()不执行的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在 HarmonyOS Next 中,textProcessing.getEntity() 返回 undefined 通常是由于以下原因:

  1. 模块导入问题:确保正确导入 @kit.NaturalLanguageKit 包,并检查 SDK 版本是否支持该 API。

  2. 权限配置缺失:在 module.json5 中添加自然语言处理权限:

"requestPermissions": [
  {
    "name": "ohos.permission.NATURAL_LANGUAGE_PROCESSING"
  }
]
  1. API 可用性检查:调用前需验证 textProcessing 是否已初始化:
if (textProcessing && typeof textProcessing.getEntity === 'function') {
  let result = await textProcessing.getEntity(...);
}
  1. 异步处理问题:确保在异步上下文中调用,但你的代码已使用 async/await,这部分正确。

  2. 实体类型兼容性:确认 EntityType.NAMEEntityType.PHONE_NO 在当前版本中有效。

建议按顺序检查以上配置,重点确认权限声明和模块初始化状态。

回到顶部