구글 번역 API를 사용하는 방법은 다음 두가지입니다.
- googletrans: 무료 API
- Google Cloud Translation API : 유료 API
googletrans는 오픈소스이며, ajax api를 사용하여 구현한 것 같습니다. 무료이지만, 하루에 사용할 수 있는 횟수가 제한되어있습니다. (구글에서 제한하는 것 같습니다.)
Google Cloud Translation는 구글에서 공식적으로 제공하는 API입니다. 500,000 글자 미만은 무료이며, 그 이상은 백만 자당 $20씩 비용을 받는 것 같습니다.
위에서 소개한 두가지 API들을 사용하는 방법에 대해서 간단히 알아보겠습니다.
1. googletrans 설치
다음과 같이 설치합니다.
$ pip install googletrans
다음과 같이 API를 사용할 수 있습니다. 입력되는 텍스트의 언어는 자동으로 추론되며, 번역할 언어의 locale을 입력하면 됩니다.
from googletrans import Translator
translator = Translator()
result = translator.translate('안녕하세요.', dest="ja")
print(result[0].text)
결과
こんにちは
아래와 같이 어떤 언어인지 확인할 수도 있습니다.
>>> translator.detect('이 문장은 한글로 쓰여졌습니다.')
# <Detected lang=ko confidence=0.27041003>
>>> translator.detect('この文章は日本語で書かれました。')
# <Detected lang=ja confidence=0.64889508>
>>> translator.detect('This sentence is written in English.')
# <Detected lang=en confidence=0.22348526>
더 자세한 내용은 googletrans를 참고해주세요.
2. Google Cloud Translation 설치
현재 API v3까지 나왔습니다. v3는 ML(Machine Learning)을 적용할 수도 있습니다.
아래와 같이 라이브러리를 설치합니다.
$ pip install --upgrade google-cloud-translate
Google API는 500,000 글자 이상부터 유료이기 때문에, Google Clould Key가 있어야 사용할 수 있습니다. Google Clould에서 프로젝트를 만들고, Translate를 등록하고 key를 받습니다. key 파일을 다운로드받고, 아래와 같은 이름으로 path를 설정합니다.
export GOOGLE_APPLICATION_CREDENTIALS="/home/.../myproject-f4f4ad4248b0.json"
라이브러리 설정은 모두 끝났습니다.
3. API v2를 사용하여 텍스트 번역
API v2는 다음과 같이 사용할 수 있습니다.
from google.cloud import translate_v2 as translate
client = translate.Client()
result = client.translate('안녕하세요', target_language='ja')
print(result['translatedText'])
결과
こんにちは
4. API v3를 사용하여 텍스트 번역
API v3는 다음과 같이 사용할 수 있습니다.
from google.cloud import translate_v3beta1 as translate
client = translate.TranslationServiceClient()
response = client.translate_text(
parent=parent,
contents=["안녕하세요"],
mime_type='text/plain', # mime types: text/plain, text/html
source_language_code='ko',
target_language_code='ja')
for translation in response.translations:
print('Translated Text: {}'.format(translation))
python외에도 Nodejs, Java 등의 언어에서 사용할 수 있도록 지원하고 있습니다. 자세한 것은 Google Cloud Translation에서 확인할 수 있습니다.
참고
Related Posts
- Python 소수점 반올림, round() 예제
- 파이썬 주석 처리, 단축키 소개
- Python - String isdigit(), 문자열이 숫자인지 확인
- Python 소수점 버림, 4가지 방법
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - String Formatting의 다양한 방법 정리(%, Str formatting, f-stirng)
- Python - os.path.join(), 폴더와 파일명으로 Path 생성
- Python - 파일을 읽고 한 줄씩 리스트에 저장
- Python - 문자열에서 줄바꿈(\n) 제거, 3가지 방법
- Python - Switch Case 구현 방법 (Match Case)
- 우분투에 Python 3.10 설치하는 방법
- Python - 문자열에서 특정 문자 제거, 3가지 방법
- Python - 함수 정의 및 호출 방법
- Python - 딕셔너리 정리 및 예제
- Python - 딕셔너리 초기화, 4가지 방법
- Python - input() 함수로 데이터 입력 받기
- Python - Tuple 사용 방법
- Python - String startswith(), 어떤 문자열로 시작하는지 확인
- Python - 날짜에서 월 이름 가져오기(숫자 -> 영어 이름 변환)
- Python - 어떤 날짜가 몇 주차인지 확인
- Python - D-Day 계산, 몇일 남았는지 날짜 세기
- Python - 날짜가 무슨 요일인지 계산
- Python - 어떤 날짜가 주말인지, 평일인지 확인
- Python - XML 생성 및 파일 저장
- Python - 특정 월의 시작 날짜, 마지막 날짜 얻기
- Python - XML 파싱, 태그 또는 요소 별로 읽기
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - Selenium에서 웹페이지의 제목 가져오는 방법
- Python - 디렉토리, 파일 사이즈 계산
- Python 버전 확인 방법 (스크립트 또는 Command line)
- Python - 함수에서 두개 이상의 값 리턴
- Python - CSV 파일 읽기, 쓰기
- Python - 코드 실행 시간 측정
- Python - 디폴트 매개변수(Default parameters)
- Python - filter() 사용 방법 및 예제