首页 > web前端 > js教程 > 带 API 的简单语言翻译器

带 API 的简单语言翻译器

WBOY
发布: 2024-08-29 13:40:11
原创
1081 人浏览过

Simple Language Translator with API

#100daysofMiva 编码挑战的第 8 天,我研究了一个简单的翻译模型,可以将一种语言翻译成另一种语言?
这是JS,这很神奇✨?

?语言翻译器脚本文档

概述

此 JavaScript 代码旨在创建一个有趣的交互式语言翻译器!它利用 MyMemory API 在不同语言之间翻译文本,并允许您交换语言、复制翻译,甚至大声朗读文本。 ??


特征

  • ?语言选择:用户可以从多种语言中进行选择,从阿姆哈拉语到祖鲁语!
  • ?语言切换:只需单击按钮即可轻松在源语言和目标语言之间切换。
  • ?文本转语音: 聆听所选语言的原始文本或翻译文本。
  • ?复制到剪贴板: 单击即可复制原始文本或翻译文本。

代码分解

语言数据

const countries = { /*...*/ } 
登录后复制

该对象包含可用的语言及其各自的国家代码。例如,“en-GB”:“English”将语言代码与其名称配对。

动态下拉菜单

selectTag.forEach((tag, id) => {
    /*...*/
});
登录后复制

此代码使用国家对象中列出的所有语言动态填充下拉菜单。第一个下拉菜单默认为英语(“en-GB”),第二个下拉菜单默认为印地语(“hi-IN”)。

语言交换

exchageIcon.addEventListener("click", () => {
    /*...*/
});
登录后复制

单击交换图标允许用户在“从”和“到”字段之间交换文本和所选语言。

实时翻译

translateBtn.addEventListener("click", () => {
    /*...*/
});
登录后复制

单击“翻译”按钮时,文本将发送到 MyMemory API,翻译后的文本将显示在“待文本”字段中。在等待响应时,会显示“正在翻译...”占位符。

文本转语音和复制

icons.forEach(icon => {
    /*...*/
});
登录后复制

此部分处理文本转语音和复制功能:

  • 语音:以所选语言大声播放文本。
  • 复制:将文本复制到剪贴板。

它是如何运作的

  1. 选择语言 ?:从下拉列表中选择您的语言。
  2. 输入或粘贴文本 ✍️:输入您要翻译的文本。
  3. 翻译 ?:点击“翻译”按钮,观看奇迹发生!
  4. 交换、聆听或复制 ???:交换语言、聆听翻译或将文本复制到剪贴板。

依赖关系

  • MyMemory API:翻译功能由 MyMemory API 提供支持。确保您有有效的互联网连接才能正常工作。

潜在的增强功能

  • 语言自动检测:自动检测输入文本的语言。
  • 高级错误处理:改进对翻译错误或 API 故障的响应。
  • 多种翻译:显示可用的替代翻译。

以下是代码的工作原理及其用途的逐步细分:

Step 1: Defining Available Languages

const countries = { /*...*/ }
登录后复制
  • What it does: This object contains key-value pairs where the key is a language-country code (like "en-GB" for English) and the value is the name of the language (like "English").
  • Purpose: This data is used to populate the language selection dropdowns so users can choose their source and target languages.

Step 2: Selecting DOM Elements

const fromText = document.querySelector(".from-text"),
      toText = document.querySelector(".to-text"),
      exchageIcon = document.querySelector(".exchange"),
      selectTag = document.querySelectorAll("select"),
      icons = document.querySelectorAll(".row i");
      translateBtn = document.querySelector("button"),
登录后复制
  • What it does: This code selects various elements from the HTML document and stores them in variables for easy access later.
    • fromText and toText: Text areas where users input text and see the translation.
    • exchageIcon: The icon used to swap languages and text.
    • selectTag: The dropdown menus for selecting languages.
    • icons: Icons for copy and speech functions.
    • translateBtn: The button that triggers the translation.

Step 3: Populating Language Dropdowns

selectTag.forEach((tag, id) => {
    for (let country_code in countries) {
        let selected = id == 0 ? country_code == "en-GB" ? "selected" : "" : country_code == "hi-IN" ? "selected" : "";
        let option = `<option ${selected} value="${country_code}">${countries[country_code]}</option>`;
        tag.insertAdjacentHTML("beforeend", option);
    }
});
登录后复制
  • What it does: This loop goes through the countries object and adds each language as an option in the language selection dropdowns.
    • If the dropdown is the first one (id == 0), English ("en-GB") is selected by default.
    • If the dropdown is the second one (id == 1), Hindi ("hi-IN") is selected by default.

Step 4: Swapping Languages and Text

exchageIcon.addEventListener("click", () => {
    let tempText = fromText.value,
        tempLang = selectTag[0].value;
    fromText.value = toText.value;
    toText.value = tempText;
    selectTag[0].value = selectTag[1].value;
    selectTag[1].value = tempLang;
});
登录后复制
  • What it does: When the swap icon is clicked, this function swaps the text between the "from" and "to" text areas as well as the selected languages.
    • tempText temporarily holds the original text from the "from-text" field.
    • tempLang temporarily holds the original language from the first dropdown.
    • The "from-text" is then replaced with the "to-text", and vice versa. The selected languages are also swapped.

Step 5: Clearing Translated Text

fromText.addEventListener("keyup", () => {
    if(!fromText.value) {
        toText.value = "";
    }
});
登录后复制
  • What it does: If the user deletes all the text from the "from-text" field, this function automatically clears the "to-text" field as well.
  • Purpose: Ensures that if the input text is cleared, the translation is cleared too, preventing confusion.

Step 6: Translating Text

translateBtn.addEventListener("click", () => {
    let text = fromText.value.trim(),
        translateFrom = selectTag[0].value,
        translateTo = selectTag[1].value;
    if(!text) return;
    toText.setAttribute("placeholder", "Translating...");
    let apiUrl = `https://api.mymemory.translated.net/get?q=${text}&langpair=${translateFrom}|${translateTo}`;
    fetch(apiUrl).then(res => res.json()).then(data => {
        toText.value = data.responseData.translatedText;
        data.matches.forEach(data => {
            if(data.id === 0) {
                toText.value = data.translation;
            }
        });
        toText.setAttribute("placeholder", "Translation");
    });
});
登录后复制
  • What it does: When the "Translate" button is clicked, this function:
    1. Extracts the text from the "from-text" field.
    2. Identifies the selected languages from the dropdowns.
    3. Sends a request to the MyMemory API with the text and selected languages.
    4. Receives the translation from the API and displays it in the "to-text" field.
    5. Updates the placeholder text while waiting for the translation to indicate that the process is ongoing.

Summary

The script allows users to translate text between different languages with a dynamic and interactive interface. Users can select languages, type in their text, translate it with a click, swap languages and text, hear the translation spoken aloud, or copy it to their clipboard.

Enjoy playing with different languages and make your translation journey fun and interactive! ?? Unto the next ?✌?✨

Check it out here
https://app.marvelly.com.ng/100daysofMiva/day-8/

Source code
https://github.com/Marvellye/100daysofMiva/blob/main/Projects%2FDay_8-Simple_language_translator

以上是带 API 的简单语言翻译器的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板