我們在閱讀外文文獻時,有些文獻是有網頁在線版本的。然后網頁有翻譯功能,可直接將英文翻譯成中文,但同時,文中的一些公式也被翻譯了,閱讀起來就很難受。
因此,這就產生一個問題:
怎么樣在翻譯網頁的同時,保留公式,只翻譯文本?
translate 屬性
在網頁中,早就規定了一個專門用於翻譯的元素屬性,叫做 translate
。
<p translate="no">請勿翻譯本段。</p>
<p>本段可被譯為任意語言。</p>
https://www.w3school.com.cn/tags/att_global_translate.asp
因此要防止元素被翻譯,則需要增加這個屬性。
MathJax
目前,網頁上的公式大多是通過 MathJax 生成的。
其生成的公式如果不是 SVG 格式的話,便會以大量的 <span>
來呈現。然后會加上相應的 id 或 class 。
這里最外層包裹着的就是 class="MathJax"
這樣的了。
而且,大部分的元素,命名都是有規律的。所以說要定位到他們並不難。
公式翻譯保留方案
由前面的介紹,可以得出一個公式翻譯保留方案:
網頁打開后,首先定位到由 MathJax
生成的公式 元素;然后給他們增加 translate="no"
這個屬性;最后再進行網頁翻譯。
簡單實現
借助 JQuery
來簡單實現:
$('math, .math, .MathJax').attr('translate','no');
臨時方案
所以,一個臨時方案是,打開要翻譯的網站,等網頁加載完畢后,按 F12 調出控制台,然后輸入上面的代碼,再翻譯(一般來說,網頁都都會引入 JQuery
這個庫的)。
油猴腳本
當然,每次這么手動是很繁瑣的,為了更好的偷懶,可以把代碼寫成 油猴腳本 。
// ==UserScript==
// @name 公式翻譯保留
// @namespace http://tampermonkey.net/
// @version 0.1
// @description 網頁翻譯時,保留公式
// @author GShang
// @require http://cdn.staticfile.org/jquery/1.8.3/jquery.min.js
// @grant GM_getResourceURL
// @grant unsafeWindow
// @grant GM_setClipboard
// @include https://www.sciencedirect.com/*
// @include https://ieeexplore.ieee.org/document/*
// @grant GM_getResourceURL
// @grant GM_xmlhttpRequest
// @grant GM_getResourceText
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_download
// @grant GM_addStyle
// @grant GM_openInTab
// @noframes Chrome
// @compatible Chrome
// @compatible Firefox
// @compatible Edge
// @compatible Safari
// @compatible Opera
// @compatible UC
// @license GPL3 license
// ==/UserScript==
(function() {
'use strict';
// 帶有公式的元素
const mathElement ='math, .math, .MathJax';
// 添加按鈕
var mathBtn = '<button id="math-btn">公式翻譯保留</button>';
$('body').append(mathBtn);
// 添加樣式
GM_addStyle('#math-btn {background:#ff3500;padding:10px 20px;color:#fff;border-radius:40px 0 0 40px;position:fixed;right:0px;top:50vh;z-index:99999999999999;border:none;height:fit-content;outline:none;cursor:grab}');
// 點擊按鈕,添加翻譯保留屬性
$('#math-btn').click(function(){
if($(mathElement).length > 0){
// console.log('該頁面存在公式!');
// alert('該頁面存在公式!');
$(mathElement).attr('translate','no');
alert('公式已被保留!');
}else{
console.log('未發現公式!');
alert('未發現公式!');
}
})
// Your code here...
})();
上述代碼中,可根據需要增加或修改對應的匹配網站:
// @include https://ieeexplore.ieee.org/document/*
其中 * 表示匹配該級別下的任意網址。
使用時,也是先等網頁加載完畢,然后點擊右邊的 “公式翻譯保留按鈕”,再在彈出的窗口中點 “確定” ,最后翻譯網頁。