如何在JavaScript中使用Google Cloud翻译API排除指定词汇?
在Google Cloud翻译API中用JavaScript排除特定词汇不翻译的实现方法
核心思路
由于无法使用例外术语表,我们可以采用占位符替换法:先将需要保留的词汇替换为不会被翻译的唯一占位符,调用API翻译处理后的文本,最后再把占位符还原为原词汇,以此实现特定词汇不被翻译的效果。
完整实现代码
function translateWithExclusions(text, targetLang = 'es', apiKey) { // 定义需要排除翻译的词汇列表 const excludedWords = ['playbook', 'ricky']; // 创建词汇与占位符的映射(用唯一前缀避免冲突) const placeholderMap = {}; let processedText = text; // 第一步:替换目标词汇为占位符 excludedWords.forEach(word => { const placeholder = `__EXCLUDE_${word.toUpperCase()}__`; placeholderMap[placeholder] = word; // 用正则匹配独立单词,避免部分匹配 const regex = new RegExp(`\\b${word}\\b`, 'gi'); processedText = processedText.replace(regex, placeholder); }); // 第二步:调用Google Cloud翻译API const xhr = new XMLHttpRequest(); xhr.open("POST", `https://translation.googleapis.com/language/translate/v2?key=${apiKey}`); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onload = function() { if (xhr.status === 200) { const response = JSON.parse(xhr.responseText); let translatedText = response.data.translations[0].translatedText; // 第三步:将占位符还原为原词汇 Object.entries(placeholderMap).forEach(([placeholder, word]) => { translatedText = translatedText.replace(new RegExp(placeholder, 'g'), word); }); // 处理格式问题(引号、&符号替换) translatedText = translatedText.replace(/"/g, '"'); translatedText = translatedText.replace(/&/g, "y"); // 输出最终结果 console.log(translatedText); // 这里可以添加后续处理逻辑,比如更新DOM等 } else { console.error('翻译请求失败:', xhr.statusText); } }; xhr.onerror = function() { console.error('网络请求出错'); }; // 构建请求参数 const params = `q=${encodeURIComponent(processedText)}&target=${targetLang}`; xhr.send(params); } // 调用示例 const originalText = 'On my "playbook" the dogs were funny. Ricky likes this playbook.'; translateWithExclusions(originalText, 'es', '你的API密钥');
代码说明
- 占位符替换:为每个需要排除的词汇生成唯一占位符(如
__EXCLUDE_PLAYBOOK__),用正则匹配独立单词进行替换,避免误替换包含目标词汇的其他单词。 - API调用:将处理后的文本发送到翻译API,此时占位符不会被翻译。
- 还原词汇:翻译完成后,把所有占位符替换回原词汇。
- 格式处理:针对API返回的转义字符(如
"、&)进行格式修正。
效果示例
原句:On my "playbook" the dogs were funny. Ricky likes this playbook.
翻译后西班牙语结果:En mi "playbook" los perros eran divertidos. Ricky le gusta este playbook.
内容的提问来源于stack exchange,提问作者Faint
相关产品推荐
相关产品推荐

