【HarmonyOS NEXT】实现文案智能识别

【需求】
实现:类似快递粘贴收发件人信息,能自成识别出收发件人姓名电话地址等。

该案例以客户报备为例,当把客户备案文本粘贴到输入框中,点击识别,能够识别出相应字段。

【步骤】

  1. 准备类型模型
interface IMatch {
  key: string
  match: RegExp | string
  valueMatch?: RegExp
}

interface IOption {
  delimiter: RegExp
  matches: IMatch[]
}

class KeyLabelMap {
  cusName: string = '客户姓名'
  cusSex: string = '性别'
  cusMobile: string = '客户电话'
  projectName: string = '报备项目'
  agentName: string = '经纪人姓名'
  agentPhone: string = '经纪人电话'
  agentIdCardNo: string = '经纪人身份证'
}

const keyLabel = new KeyLabelMap()

const DefaultOptions: IOption = {
  delimiter: /[;;,,\n]/,
  matches: [
    { key: 'cusName', match: /客户姓名/ },
    { key: 'cusSex', match: /性别/, valueMatch: /男|女|先生|女士|小姐/ },
    { key: 'cusMobile', match: /客户(联系方式|电话|手机号(码)?)/ },
    { key: 'projectName', match: /[(报备)(带看)]项目/ },
    { key: "agentName", match: /(经纪人|带看人(员)?)姓名/ },
    { key: "agentPhone", match: /(经纪人|带看人(员)?)(联系方式|电话|手机号(码)?)/ },
    { key: "agentIdCardNo", match: /(经纪人|带看人(员)?)(身份证号(码)?)/ },
  ]
}
  1. 编写页面UI

@Entry
@Component
struct SmartPastingPage {
  @State textAreaValue: string = ''
  @State formData: Record<string, string> = {}

  build() {
    Column({ space: 10 }) {
      TextArea({ text: $$this.textAreaValue })
        .height(200)
        .borderRadius(8)
      Button('识别')
        .onClick(() => {
          this.formData = recognitionInfo(this.textAreaValue)
        })

      List({ space: 5 }) {
        ForEach(DefaultOptions.matches, (item: IMatch) => {
          ListItem() {
            Text(`${(keyLabel as object)[item.key]}: ${this.formData[item.key] || ''}`)
          }
        })
      }
    }
    .width('100%')
    .height('100%')
    .padding(20)
  }
}
  1. 编写识别方法

function recognitionInfo(txt: string) {
  const delimiter = DefaultOptions.delimiter
  const matches = DefaultOptions.matches

  let tmpValues = txt.split(delimiter)
  tmpValues = tmpValues.filter(item => item)

  let tmpKey = ''
  let tmpVal = ''
  let resMap: Record<string, string> = {}
  matches.forEach(matchItem => {

    let i = 0
    let length = tmpValues.length
    let itemList: string[] = []

    while (i < length) {
      itemList = tmpValues[i].split(/[::]/)
      tmpKey = itemList.shift()?.trim() || ''
      tmpVal = itemList.join(':')?.trim() || ''

      if ((matchItem.match instanceof RegExp) && matchItem.match.test(tmpKey)) {
        resMap[matchItem.key] = tmpVal
        tmpValues.splice(i, 1)
        length = length - 1
      } else {
        i++
      }
    }
  })

  return resMap
}

【测试】
将复制以下本文,粘贴到文本框内,点识别

客户姓名:大大;性别:男;客户电话:13812345678,带看人姓名:牛德华,经纪人电话:13412341234
  带看项目:天上人奸;经纪人身份证号:44013812345678x

【效果图】

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值