2017-07-30 68 views
1

我在文档中有一个单词的数组,其坐标位置是文本,我想将它们转换为句子。 我阵列输入:将单词数组从文档的坐标转换为句子

[ 
    { 
     "bounds": [ 
      { 
      "x": 10, 
      "y": 10 
      }, 
      { 
      "x": 15, 
      "y": 10 
      }, 
      { 
      "x": 15, 
      "y": 15 
      }, 
      { 
      "x": 10, 
      "y": 15 
      } 
     ], 
     "desc": "Hey" 
     }, 
    { 
     "bounds": [ 
      { 
      "x": 18, 
      "y": 10 
      }, 
      { 
      "x": 24, 
      "y": 10 
      }, 
      { 
      "x": 24, 
      "y": 15 
      }, 
      { 
      "x": 18, 
      "y": 15 
      } 
     ], 
     "desc": "Name" 
     }, 
      { 
     "bounds": [ 
      { 
      "x": 18, 
      "y": 20 
      }, 
      { 
      "x": 24, 
      "y": 20 
      }, 
      { 
      "x": 24, 
      "y": 25 
      }, 
      { 
      "x": 18, 
      "y": 25 
      } 
     ], 
     "desc": "What" 
     }, 
    { 
     "bounds": [ 
      { 
      "x": 18, 
      "y": 20 
      }, 
      { 
      "x": 24, 
      "y": 20 
      }, 
      { 
      "x": 24, 
      "y": 25 
      }, 
      { 
      "x": 18, 
      "y": 25 
      } 
     ], 
     "desc": "Sup" 
     } 
] 

程序输出应该是:

Hey Name 
What Sup 
  • 的坐标是不准确的只是一个例子,也是算法需要处理的是在中间的话句子和其他极端情况。

它是我能做到的最好的方式(理想地用JavaScript实现)?

+2

请解释一下,要如何实现这一目标。用“机器学习”或“算法”来标记这个问题并不能解释你想要做什么。 –

+0

@MichaelHirschler我正在寻找最好的方法来做到这一点...... – gal

+2

@gal这对问题毫无帮助。它是什么”?你想要将一组单词转换成句子。数组的结构是什么?你想创建什么类型的句子? – victor

回答

0

您可以使用散列表并对行和位置进行排序,然后按照此顺序返回文本。

var data = [{ bounds: [{ x: 10, y: 10 }, { x: 15, y: 10 }, { x: 15, y: 15 }, { x: 10, y: 15 }], desc: "Hey" }, { bounds: [{ x: 18, y: 10 }, { x: 24, y: 10 }, { x: 24, y: 15 }, { x: 18, y: 15 }], desc: "Name" }, { bounds: [{ x: 18, y: 20 }, { x: 24, y: 20 }, { x: 24, y: 25 }, { x: 18, y: 25 }], desc: "What" }, { bounds: [{ x: 18, y: 20 }, { x: 24, y: 20 }, { x: 24, y: 25 }, { x: 18, y: 25 }], desc: "Sup" }], 
 
    hash = {}, 
 
    result; 
 

 
data.forEach(function (a) { 
 
    hash[a.bounds[0].y] = hash[a.bounds[0].y] || {}; 
 
    hash[a.bounds[0].y][a.bounds[0].x] = hash[a.bounds[0].y][a.bounds[0].x] || []; 
 
    hash[a.bounds[0].y][a.bounds[0].x].push({ desc: a.desc, end: a.bounds[2] }); 
 

 
}); 
 

 
result = Object.keys(hash) 
 
    .sort((a, b) => a - b) 
 
    .map(k => Object.keys(hash[k]) 
 
     .sort((a, b) => a - b) 
 
     .reduce((r, l) => [...r, ...hash[k][l].map(c => c.desc)], []) 
 
     .join(' ') 
 
    ) 
 
    .join('\n'); 
 
    
 
console.log(result); 
 
console.log(hash);
.as-console-wrapper { max-height: 100% !important; top: 0; }