2017-07-30 67 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; }