웹 프론트엔드 JS 튜토리얼 API를 사용한 간단한 언어 번역기

API를 사용한 간단한 언어 번역기

Aug 29, 2024 pm 01:40 PM

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로 전송되고 번역된 텍스트가 'to-text' 필드에 표시됩니다. 응답을 기다리는 동안 "번역 중..." 자리 표시자가 표시됩니다.

텍스트 음성 변환 및 복사

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

JavaScript로 문자열 문자를 교체하십시오 JavaScript로 문자열 문자를 교체하십시오 Mar 11, 2025 am 12:07 AM

JavaScript로 문자열 문자를 교체하십시오

jQuery 날짜가 유효한지 확인하십시오 jQuery 날짜가 유효한지 확인하십시오 Mar 01, 2025 am 08:51 AM

jQuery 날짜가 유효한지 확인하십시오

jQuery는 요소 패딩/마진을 얻습니다 jQuery는 요소 패딩/마진을 얻습니다 Mar 01, 2025 am 08:53 AM

jQuery는 요소 패딩/마진을 얻습니다

10 JQuery Accordions 탭 10 JQuery Accordions 탭 Mar 01, 2025 am 01:34 AM

10 JQuery Accordions 탭

10 JQuery 플러그인을 확인할 가치가 있습니다 10 JQuery 플러그인을 확인할 가치가 있습니다 Mar 01, 2025 am 01:29 AM

10 JQuery 플러그인을 확인할 가치가 있습니다

노드 및 HTTP 콘솔로 HTTP 디버깅 노드 및 HTTP 콘솔로 HTTP 디버깅 Mar 01, 2025 am 01:37 AM

노드 및 HTTP 콘솔로 HTTP 디버깅

사용자 정의 Google 검색 API 설정 자습서 사용자 정의 Google 검색 API 설정 자습서 Mar 04, 2025 am 01:06 AM

사용자 정의 Google 검색 API 설정 자습서

jQuery div에 스크롤 바를 추가합니다 jQuery div에 스크롤 바를 추가합니다 Mar 01, 2025 am 01:30 AM

jQuery div에 스크롤 바를 추가합니다

See all articles