PYTHON/번역기

DeepL API 사용하여 번역 코드 생성

죠으니 2024. 2. 29. 16:34

설치

pip install deepl

 

기본 코드

- 텍스트만 넣어서 번역하는 경우와 파일 전체를 번역하는 경우 두 가지 예시 코드 입니다.

 

텍스트 번역

def text_translation():

    auth_key = "deepl API키"
    translator = deepl.Translator(auth_key)
 
    message = 'Dạo này bạn học tiếng Việt không?'
    result = translator.translate_text(message, target_lang="KO")
    
    return result.text

 

파일 전체 번역

 

ex 1)

def file_context(file_path):
    with open(file_path, 'r',encoding='UTF8') as f:    # file_path : 파일 경로
        text = f.read()
    return text

def text_translation():

    auth_key = "deepl API키"
    translator = deepl.Translator(auth_key)
   
    file_path = "파일 경로"
    message = file_context(file_path)
 
    message = 'Dạo này bạn học tiếng Việt không?'
    result = translator.translate_text(message, target_lang="KO")
    
    return result.text

 

ex 2)

def file_translation():

    auth_key = "deepl API키"   # api키
    translator = deepl.Translator(auth_key)

    translator.translate_document_from_filepath(
        "원문 파일 경로",         # 원문
        "번역본 저장할 파일 경로",     # 번역
        target_lang="KO"
    )