Skip to content

Instantly share code, notes, and snippets.

@3014zhangshuo
Last active June 16, 2020 10:49
Show Gist options
  • Save 3014zhangshuo/5d19f43c2cdd1cf02f1d534be78d624b to your computer and use it in GitHub Desktop.
Save 3014zhangshuo/5d19f43c2cdd1cf02f1d534be78d624b to your computer and use it in GitHub Desktop.
自动翻译 rails 多语言文件
const fs = require('fs')
const translate = require('google-translate-api')
const langCodeFileMap = {
bn: 'bn',
en: 'en-us',
de: 'de',
el: 'el',
es: 'es',
fr: 'fr',
hi: 'hi',
id: 'id',
it: 'it',
ja: 'ja',
ko: 'ko',
pt: 'pt',
ru: 'ru',
th: 'th',
tr: 'tr',
vi: 'vi',
'zh-cn': 'cn',
'zh-tw': 'zh-HK'
}
const langKey = process.argv[2]
const originalText = process.argv[3]
const dir = '/Users/zhangshuo/Documents/xx_desk/xx_desk_proj/config/lang_hubs'
Object.keys(langCodeFileMap).forEach(targetLang =>
startTranslate(originalText, targetLang, (file, translatedText) => {
let text = `${langKey}: ${translatedText}`
fs.readFile(file, function (err, data) {
if (err) console.log(err)
if (data.indexOf(langKey) < 0){
fs.writeFile(file, text, { flag: 'a+' }, (err) => {
if (err) console.log(err)
console.log("Successfully Written to File.")
})
}
})
})
)
function startTranslate(text, to_lang, callback) {
translate(text, { from: 'zh-cn', to: to_lang }).then(res => {
callback.call(null, findfile(to_lang), res.text)
}).catch(err => {
console.error(err)
})
}
function findfile(lang) {
return `${dir}/${langCodeFileMap[lang]}.yml`
}
@3014zhangshuo
Copy link
Author

3014zhangshuo commented Jun 15, 2020

使用 google-translate-api 翻译,自动把翻译结果写入多语言文件中。

如果卡主,需要更改 node_modules/google-translate-api/index.jsnode_modules/google-translate-token/index.js 中的请求地址 https://translate.google.com 改成 https://translate.google.cn

@3014zhangshuo
Copy link
Author

3014zhangshuo commented Jun 15, 2020

node translate.js i18n_key 需要翻译的中文

node translate.js macro.forbidden_create 没有权限创建宏

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