搜尋
首頁web前端js教程帶有 API 的簡單語言翻譯器

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 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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript引擎:比較實施JavaScript引擎:比較實施Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

超越瀏覽器:現實世界中的JavaScript超越瀏覽器:現實世界中的JavaScriptApr 12, 2025 am 12:06 AM

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

使用Next.js(後端集成)構建多租戶SaaS應用程序使用Next.js(後端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:23 AM

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

如何使用Next.js(前端集成)構建多租戶SaaS應用程序如何使用Next.js(前端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:22 AM

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript:探索網絡語言的多功能性JavaScript:探索網絡語言的多功能性Apr 11, 2025 am 12:01 AM

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

JavaScript的演變:當前的趨勢和未來前景JavaScript的演變:當前的趨勢和未來前景Apr 10, 2025 am 09:33 AM

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

神秘的JavaScript:它的作用以及為什麼重要神秘的JavaScript:它的作用以及為什麼重要Apr 09, 2025 am 12:07 AM

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python還是JavaScript更好?Python還是JavaScript更好?Apr 06, 2025 am 12:14 AM

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。1.Python以简洁语法和丰富库生态著称,适用于数据分析和Web开发。2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用