首頁 > web前端 > js教程 > 主體

帶有 API 的簡單語言翻譯器

WBOY
發布: 2024-08-29 13:40:11
原創
1055 人瀏覽過

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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!