当前位置:网站首页>Remember to build wheels repeatedly at one time (the setting instructions of obsidian plug-in are translated into Chinese)

Remember to build wheels repeatedly at one time (the setting instructions of obsidian plug-in are translated into Chinese)

2022-07-04 20:56:00 ShuangLian

gossip #Java Script

Because I am not good at using English Obsidian when , The setting of some plug-ins in English is very painful . So I have the idea of writing a translation plug-in introduction and setting script . See some translation methods written by predecessors , It's terrible to see . I have to do it manually . Should this be written so well that it can be translated into Chinese with only one key ?
ok . I admit it's a little difficult . The translation engine should use the well-known . I think its translation accuracy of professional terms is still very high .

  1. extract main.js Words and sentences needed in
  2. Use the right way API To translate and generate the corresponding file
  3. Use Quicker Plug in one click replacement

I don't want to write the process in detail here , Post the code directly . Integrate again when you have time .
main.js Processing code :( It was used FastJson The tools inside , Import required )

import com.alibaba.fastjson.JSON;

import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ShuangLian
 * @date 2022/7/4 1:07
 */
public class test {
    public static void main(String[] args) throws IOException {
        //  The plug-in to be translated corresponds to main.js file 
        File file = new File("C:\\Users\\91324\\Documents\\Projects\\IdeaProjects\\Test-demo\\src\\test\\java\\cn\\lian\\main.js");
        System.out.println(file.getAbsolutePath());
        FileInputStream stream = new FileInputStream(file);
        InputStreamReader reader = new InputStreamReader(stream);
        BufferedReader bufferedReader = new BufferedReader(reader);
        LinkedList<String> list = new LinkedList<>();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            //  Match the part to be translated 
            String s_setName = "setName\\([^\\)]+\\)";
            String s_addOption = "addOption\\([^\\)]+\\)";
            String s_setDesc = "setDesc\\([^\\)]+\\)*\"\\)";
            String s_name = "name: \".*\",";
            //  Use regular to find matches 
            List<String> linkedList;
            if ((linkedList = find(s_setName, line)).size() != 0) {
                for (String s : linkedList) {
                    list.add(s.substring(9, s.length() - 2));
                }
            }
            if ((linkedList = find(s_setDesc, line)).size() != 0) {
                for (String s : linkedList) {
                    list.add(s.substring(9, s.length() - 2));
                }
            }
            if ((linkedList = find(s_addOption, line)).size() != 0) {
                for (String ss : linkedList) {
                    String substring = ss.substring(10, ss.length() - 1);
                    String[] split = substring.split(",");
                    for (String s : split) {
                        s = s.strip();
                        list.add(s.substring(1, s.length() - 1));
                    }
                }
            }
            if ((linkedList = find(s_name, line)).size() != 0) {
                for (String s : linkedList) {
                    list.add(s.substring(7, s.length() - 2));
                }
            }
        }
        System.out.println(list);
        bufferedReader.close();
        //  Output Chinese English comparison .txt
        File file1 = new File(".\\test2.txt");
        FileOutputStream fileOutputStream = new FileOutputStream(file1);
        //  Specify the output file code as gbk, I don't know why to replace the plug-in 2b Don't use UTF-8
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "gbk");
//        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
        BufferedWriter writer = new BufferedWriter(outputStreamWriter);
        for (String s : list) {
            writer.append(s).append("\n");
            String query = FanyiV3Demo.query(s);
            String translation = JSON.parseObject(query).getJSONArray("translation").get(0).toString();
            writer.append(translation).append("\n");
        }
        writer.flush();
    }
    public static List<String> find(String regex, String str) {
        List<String> strings = new LinkedList<>();
        Pattern p = Pattern.compile(regex);
        Matcher matcher = p.matcher(str);
        while (matcher.find()) {
            String fundStr = str.substring(matcher.start(), matcher.end());
            System.out.println(fundStr);
            strings.add(fundStr);
        }
        return strings;
    }
}

Proper translation Java SDK Refit


/**
 * @author ShuangLian
 * @date 2022/7/4 3:49
 */

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;


/**
 *  Provided by Youdao , Call directly query The method can 
 *  Return to example :
 * {
 *     "tSpeakUrl": "https://openapi.youdao.com/ttsapi?",
 *     "requestId": "afc14ed2-e6ca-49fe-8f8f-b36e6ff5bbaa",
 *     "query": "Preview on Hover for File Links",
 *     "translation": [
 *         " Preview hover file link "
 *     ],
 *     "errorCode": "0",
 *     "dict": {
 *         "url": "yddict://m.youdao.com/dict?le=eng&q=Preview+on+Hover+for+File+Links"
 *     },
 *     "webdict": {
 *         "url": "http://mobile.youdao.com/dict?le=eng&q=Preview+on+Hover+for+File+Links"
 *     },
 *     "l": "en2zh-CHS",
 *     "isWord": false,
 *     "speakUrl": "https://openapi.youdao.com/ttsapi?"
 * }
 */
public class FanyiV3Demo {

    private static Logger logger = LoggerFactory.getLogger(FanyiV3Demo.class);

    private static final String YOUDAO_URL = "https://openapi.youdao.com/api";
	//  Go to Youdao to check , You can't use it directly here 
    private static final String APP_KEY = "1fcc4";
	//
    private static final String APP_SECRET = "LgA5Wxpm60KP7nyuGp";

    public static void main(String[] args) throws IOException {

        Map<String, String> params = new HashMap<String, String>();
        String q = "Decrease body font size";
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("from", "en");
        params.put("to", "zh-CHS");
        params.put("signType", "v3");
        String curtime = String.valueOf(System.currentTimeMillis() / 1000);
        params.put("curtime", curtime);
        String signStr = APP_KEY + truncate(q) + salt + curtime + APP_SECRET;
        String sign = getDigest(signStr);
        params.put("appKey", APP_KEY);
        params.put("q", q);
        params.put("salt", salt);
        params.put("sign", sign);
        params.put("vocabId", " Your user Thesaurus ID");
        /**  Processing results  */
        requestForHttp(YOUDAO_URL, params);
    }

    public static String query(String Str) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        String q = Str;
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("from", "en");
        params.put("to", "zh-CHS");
        params.put("signType", "v3");
        String curtime = String.valueOf(System.currentTimeMillis() / 1000);
        params.put("curtime", curtime);
        String signStr = APP_KEY + truncate(q) + salt + curtime + APP_SECRET;
        String sign = getDigest(signStr);
        params.put("appKey", APP_KEY);
        params.put("q", q);
        params.put("salt", salt);
        params.put("sign", sign);
        params.put("vocabId", " Your user Thesaurus ID");
        /**  Processing results  */
        return requestForHttp(YOUDAO_URL, params);
    }

    public static String requestForHttp(String url, Map<String, String> params) throws IOException {

        String json = null;
        /**  establish HttpClient */
        CloseableHttpClient httpClient = HttpClients.createDefault();

        /** httpPost */
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
        Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> en = it.next();
            String key = en.getKey();
            String value = en.getValue();
            paramsList.add(new BasicNameValuePair(key, value));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(paramsList, "UTF-8"));
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        try {
            Header[] contentType = httpResponse.getHeaders("Content-Type");
            logger.info("Content-Type:" + contentType[0].getValue());
            if ("audio/mp3".equals(contentType[0].getValue())) {
                // If the response is wav
                HttpEntity httpEntity = httpResponse.getEntity();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                httpResponse.getEntity().writeTo(baos);
                byte[] result = baos.toByteArray();
                EntityUtils.consume(httpEntity);
                if (result != null) {// Synthesis successful 
                    String file = " Synthetic audio storage path " + System.currentTimeMillis() + ".mp3";
                    byte2File(result, file);
                }
            } else {
                /**  The response is not an audio stream , Display results directly  */
                HttpEntity httpEntity = httpResponse.getEntity();
                json = EntityUtils.toString(httpEntity, "UTF-8");
                EntityUtils.consume(httpEntity);
                logger.info(json);
                System.out.println(json);
            }
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                logger.info("## release resouce error ##" + e);
            }
        }
        return json;
    }


    /**
     *  Generate encrypted fields 
     */
    public static String getDigest(String string) {
        if (string == null) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        byte[] btInput = string.getBytes(StandardCharsets.UTF_8);
        try {
            MessageDigest mdInst = MessageDigest.getInstance("SHA-256");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    /**
     * @param result  Audio byte stream 
     * @param file    Storage path 
     */
    private static void byte2File(byte[] result, String file) {
        File audioFile = new File(file);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(audioFile);
            fos.write(result);

        } catch (Exception e) {
            logger.info(e.toString());
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static String truncate(String q) {
        if (q == null) {
            return null;
        }
        int len = q.length();
        String result;
        return len <= 20 ? q : (q.substring(0, 10) + len + q.substring(len - 10, len));
    }
}

There's another problem :
Quicker Plug ins are just replacement functions , It is possible to replace words in the text . Here we need to use regular matching again . Simply use java Let's deal with it .

原网站

版权声明
本文为[ShuangLian]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041913296037.html