Skip to content

Instantly share code, notes, and snippets.

@s-hiiragi
Last active August 2, 2022 02:27
Show Gist options
  • Save s-hiiragi/c2c2343541f152d0318a4300a265da51 to your computer and use it in GitHub Desktop.
Save s-hiiragi/c2c2343541f152d0318a4300a265da51 to your computer and use it in GitHub Desktop.
選択した英文を日本語に翻訳するサクラエディタマクロ
/**
* @file 選択した英文を日本語に翻訳
*
* 注:Shift_JISで保存してください (サクラエディタマクロの制約事項)
*/
var text = Editor.GetSelectedString(0)
.replace(/\r\n/g, '\n')
.replace(/\t/g, '')
.replace(/\. /g, '.\n');
var lines = text
.split('\n'); // avoid ie bug
for (var i = 0; i < lines.length; i++) {
lines[i] = lines[i]
.replace(/^\s+|\s+$/g, '');
}
var sentences = [];
var tmp = [];
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
tmp.push(line);
if (line == '' || /\.$/.test(line)) {
sentences.push(tmp.join(' '));
tmp = [];
}
}
if (tmp.length > 0) {
sentences.push(tmp.join(' '));
}
var newline = ['\r\n', '\r', '\n'][Editor.GetLineCode()];
var formattedText = sentences.join(newline) + newline;
Editor.InsText(formattedText);
// IEを使ってGoogle翻訳結果を取得
// 参考: http://language-and-engineering.hatenablog.jp/entry/20090713/p1
var url = 'https://translate.google.com/?hl=ja#en/ja/' + encodeURIComponent(formattedText);
var ie = new ActiveXObject('InternetExplorer.Application');
ie.Visible = false;
ie.Navigate(url);
while(ie.Busy || ie.readystate != 4) {
Sleep(100);
}
Sleep(1000);
var translatedText = ie.document.querySelector('#result_box').textContent;
ie.Quit();
Editor.InsText(newline);
Editor.InsText(translatedText);
@i4sorcerer
Copy link

ありがとう、とても便利ですね。

@i4sorcerer
Copy link

もし 日本語から英語まで欲しいですが、var url = 'https://translate.google.com/?hl=ja#en/ja/' + encodeURIComponent(formattedText);
上記のURLの修正だけでいいですか?
よろしくお願いいたします。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment