You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何将OCR识别文本按预定义key转换为对象?

OCR识别文本转结构化对象最优实现方案

核心思路

因为提前明确了需要提取的固定key(name、color、type),最优方案是以固定key为锚点做字符串分割提取,完全跳过识别可能出错的分隔符(冒号、加号等),从根源规避分隔符识别误差的问题,实现逻辑如下:

  • 预设固定key的映射表,支持大小写不敏感匹配,适配OCR输出的首字母大写格式
  • 遍历每个key,在原始文本中定位key的位置,截取当前key之后、下一个key之前的内容作为当前key的value
  • 对截取的value做前后清洗,移除多余的分隔符、空格等无效字符
  • 最终拼接为结构化对象输出

JavaScript 实现代码

// 预定义key映射:键为OCR可能输出的匹配字段(不区分大小写),值为输出对象的标准key
const KEY_MAPPING = {
  name: 'name',
  color: 'color',
  type: 'type'
}
const MATCH_KEYS = Object.keys(KEY_MAPPING)

function parseCardOcrText(rawText) {
  const structuredResult = {}
  const lowerRawText = rawText.toLowerCase()

  MATCH_KEYS.forEach((currentKey, index) => {
    // 定位当前key在文本中的起始位置
    const keyStartIndex = lowerRawText.indexOf(currentKey)
    if (keyStartIndex === -1) {
      structuredResult[KEY_MAPPING[currentKey]] = ''
      return
    }
    // 计算当前key的结束位置
    const keyEndIndex = keyStartIndex + currentKey.length
    // 定位下一个key的起始位置,没有下一个key则取文本末尾
    const nextKeyStartIndex = index < MATCH_KEYS.length - 1 
      ? lowerRawText.indexOf(MATCH_KEYS[index + 1], keyEndIndex)
      : rawText.length

    // 截取value并清洗前后无效字符
    const rawValue = rawText.slice(keyEndIndex, nextKeyStartIndex)
    const cleanedValue = rawValue.replace(/^[\s:+*#@!~&]+|[\s:+*#@!~&]+$/g, '').trim()
    structuredResult[KEY_MAPPING[currentKey]] = cleanedValue
  })

  return structuredResult
}

// 测试用例
const testText1 = "Name :Hulk Color + Green Type Hero"
const testText2 = "Name :Venom Color :Black Type Anti Hero"
console.log(parseCardOcrText(testText1))
// 输出:{ name: 'Hulk', color: 'Green', type: 'Hero' }
console.log(parseCardOcrText(testText2))
// 输出:{ name: 'Venom', color: 'Black', type: 'Anti Hero' }

方案优势

  • 鲁棒性强:完全不依赖分隔符的识别结果,只要固定key的OCR识别正确就能正常解析,适配各种分隔符识别误差场景
  • 扩展性好:后续需要新增提取字段时,只需要在KEY_MAPPING中新增对应映射即可,无需修改核心逻辑
  • 性能优异:仅做单次遍历和简单的字符串截取、清洗,没有复杂正则回溯,运算效率高

如果需要进一步提升容错率,可以对key做模糊匹配(比如用编辑距离判断识别出的近似字符串是否属于预设key),适配OCR把Name识别为Nane这类拼写误差场景。


内容的提问来源于stack exchange,提问作者Matius Nugroho Aryanto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 23:30:01