Search code examples
google-apps-scriptgoogle-apinlptranslationgoogle-docs

How can I put every sentence of a text in a row of a table next to its translation in a Google Document?


I want to put a text to be translated in a Google Doc so that every sentence is in its own row of a table. In each row of the next column is the corresponding, machine-translated sentence. Finally, there is a third blank column where I will write my own translation for each sentence.

Like so

What would some command line code look like for accessing the specific Google Doc, inserting a table, splitting the text on each sentence, and then writing each sentence to a row of the table?

I am aware of Google API, but I have struggled with authentication problems so far. If someone can sketch out a general outline of what my script should look like, hopefully I can fill in the details.

I am trying my best to meet Stack Overflow's post guidelines, so if the question is not a good one, I'm happy to reformulate it. My question is multi-part, so I prefer to ask the broader version first, before breaking it into smaller aspects.


Solution

  • Try this:

    function translate() {
      var doc = DocumentApp.openById('documentID');
      var body = doc.getBody();
      var str = "An elephant is the biggest living animal on land. It is quite huge in size. It is usually black or grey in colour. Elephants have four legs, a long trunk and two white tusks near their trunk. Apart from this, they have two big ears and a short tail. Elephants are vegetarian. They eat all kinds of plants especially bananas. They are quite social, intelligent and useful animals. They are used to carry logs of wood from one place to another. They are good swimmers.";
      //Split paragraph into sentences.
      var result = str.match( /[^\.!\?]+[\.!\?]+/g ).map(str => str.trim());;
      var translated = [];
      result.forEach(res => {
        translated.push(LanguageApp.translate(res, 'en', 'es'));
      })
    
      var table = body.appendTable();
      for(var i = 0; i <= result.length; i++){
        var tr = table.appendTableRow();
        if(i == 0){
          tr.appendTableCell("Origin");
          tr.appendTableCell("Translated");
          tr.appendTableCell("");
        }else{
          tr.appendTableCell(result[i-1]);
          tr.appendTableCell(translated[i-1]);
          tr.appendTableCell("");
        }
      }
    }
    

    Output:

    output

    References: