웹 프론트엔드 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 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

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

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

JavaScript 엔진 : 구현 비교 JavaScript 엔진 : 구현 비교 Apr 13, 2025 am 12:05 AM

각각의 엔진의 구현 원리 및 최적화 전략이 다르기 때문에 JavaScript 엔진은 JavaScript 코드를 구문 분석하고 실행할 때 다른 영향을 미칩니다. 1. 어휘 분석 : 소스 코드를 어휘 단위로 변환합니다. 2. 문법 분석 : 추상 구문 트리를 생성합니다. 3. 최적화 및 컴파일 : JIT 컴파일러를 통해 기계 코드를 생성합니다. 4. 실행 : 기계 코드를 실행하십시오. V8 엔진은 즉각적인 컴파일 및 숨겨진 클래스를 통해 최적화하여 Spidermonkey는 유형 추론 시스템을 사용하여 동일한 코드에서 성능이 다른 성능을 제공합니다.

Python vs. JavaScript : 학습 곡선 및 사용 편의성 Python vs. JavaScript : 학습 곡선 및 사용 편의성 Apr 16, 2025 am 12:12 AM

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

C/C에서 JavaScript까지 : 모든 것이 어떻게 작동하는지 C/C에서 JavaScript까지 : 모든 것이 어떻게 작동하는지 Apr 14, 2025 am 12:05 AM

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

JavaScript 및 웹 : 핵심 기능 및 사용 사례 JavaScript 및 웹 : 핵심 기능 및 사용 사례 Apr 18, 2025 am 12:19 AM

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

자바 스크립트 행동 : 실제 예제 및 프로젝트 자바 스크립트 행동 : 실제 예제 및 프로젝트 Apr 19, 2025 am 12:13 AM

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.

JavaScript 엔진 이해 : 구현 세부 사항 JavaScript 엔진 이해 : 구현 세부 사항 Apr 17, 2025 am 12:05 AM

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python vs. JavaScript : 커뮤니티, 라이브러리 및 리소스 Python vs. JavaScript : 커뮤니티, 라이브러리 및 리소스 Apr 15, 2025 am 12:16 AM

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

Python vs. JavaScript : 개발 환경 및 도구 Python vs. JavaScript : 개발 환경 및 도구 Apr 26, 2025 am 12:09 AM

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.

See all articles