- Google Apps Scriptでドキュメント上で選択している文字列を翻訳します。
- LanguageAppクラスのtranslateメソッドで文字列を翻訳します。
- translateメソッドで指定できる言語は「Using REST – Google Translate API – Google Developers」に記載されています。
- translateメソッドのsourceLanguageを空白にすることで、元の文字列の言語を自動判別します。
var ui = DocumentApp.getUi();
function onOpen(e){
ui.createMenu('翻訳メニュー').addItem('選択文字列の翻訳', 'translateText').addToUi();
}
function translateText(){
var text = getSelectedText();
if(text.length == 0){
ui.alert('文字列が選択されていません。');
}else{
ui.alert('元の文字列:' + text + '\n日本語訳:' + LanguageApp.translate(text, '', 'ja')); //元の文字列の言語:自動判別
}
}
//選択文字列を取得
function getSelectedText(){
var ret = "";
var selection = DocumentApp.getActiveDocument().getSelection();
if(selection){
var text = [];
var elements = selection.getRangeElements();
for(var i = 0; i < elements.length; i++){
if(elements[i].isPartial()){
var element = elements[i].getElement().asText();
var startIndex = elements[i].getStartOffset();
var endIndex = elements[i].getEndOffsetInclusive();
text.push(element.getText().substring(startIndex, endIndex + 1));
}else{
var element = elements[i].getElement();
if(element.editAsText){
var elementText = element.asText().getText();
if (elementText != ''){
text.push(elementText);
}
}
}
}
if(text.length !== 0) ret = text;
}
return ret;
}
- Class LanguageApp
- https://developers.google.com/apps-script/reference/language/language-app?hl=ja
- getActiveDocument()
- https://developers.google.com/apps-script/reference/document/document-app?hl=ja#getActiveDocument%28%29
- getSelection()
- https://developers.google.com/apps-script/reference/document/document?hl=ja#getSelection%28%29
- getRangeElements()
- https://developers.google.com/apps-script/reference/document/range?hl=ja#getRangeElements%28%29
- isPartial()
- https://developers.google.com/apps-script/reference/document/range-element?hl=ja#isPartial%28%29
- getElement()
- https://developers.google.com/apps-script/reference/document/range-element?hl=ja#getElement%28%29
- asText()
- https://developers.google.com/apps-script/reference/document/element?hl=ja#asText%28%29
- getStartOffset()
- https://developers.google.com/apps-script/reference/document/range-element?hl=ja#getStartOffset%28%29
- getEndOffsetInclusive()
- https://developers.google.com/apps-script/reference/document/range-element?hl=ja#getEndOffsetInclusive%28%29


















この記事へのコメントはありません。