developers Naver의 Open API 중 파파고 번역을 활용하여 번역하기
============================================================================
text문장 번역하기
from requests import Request, Session
clientId = "sMD9gukzyGkgBxN2xe4G" # 애플리케이션 클라이언트 아이디값";
clientSecret = "eb7DgdcJMY" # 애플리케이션 클라이언트 시크릿값";
apiURL = "https://openapi.naver.com/v1/papago/n2mt"
s = Session()
text = "안녕하세요. 오늘 기분은 어떻습니까?"
data = {
'source': 'ko',
'target': 'en',
'text': text
}
headers = {
"X-Naver-Client-Id": clientId,
"X-Naver-Client-Secret": clientSecret
}
req = Request('POST', apiURL, data=data, headers=headers) # 페이지 header값으로 요청을 하고 text 변환 코드를 전달
# 서버가 가진 클라이언트가 접속할 때 정보로 생성된 Session의 객체를 통해 값을 리턴받는다.
prepared = req.prepare() # 서버와 연결할 1. 준비단계
res = s.send(prepared) # 2. 세션을 통해 연결고리를 만든다. 데이터 변환 코드 전송
# 결과를 리턴받고 출력한다.
res_json = res.json()
print(res_json)
print(res_json["message"]["result"]["translatedText"])
#result
{'message': {'@type': 'response', '@service': 'naverservice.nmt.proxy', '@version': '1.0.0', 'result': {'srcLangType': 'ko', 'tarLangType': 'en', 'translatedText': 'Hello. How are you doing today?', 'engineType': 'N2MT', 'pivot': None}}}
Hello. How are you doing today?
============================================================================
.txt파일의 문장을 읽어와 번역해서 파일로 저장하기
# 파파고에서 어플리케이션을 등록하고 id와 pw를 받아서 한글문서를 번역해서 영어문서로 저장해보자.
from requests import Request, Session
clientId = "sMD9gukzyGkgBxN2xe4G" # 애플리케이션 클라이언트 아이디값";
clientSecret = "eb7DgdcJMY" # 애플리케이션 클라이언트 시크릿값";
apiURL = "https://openapi.naver.com/v1/papago/n2mt"
s = Session()
headers = {
"X-Naver-Client-Id": clientId,
"X-Naver-Client-Secret": clientSecret
}
file = open("mydata.txt", "r", encoding='UTF-8')
file_out = open("mydata_res.txt", "w", encoding='UTF-8')
while True:
line = file.readline()
data = {
'source': 'ko',
'target': 'en',
'text': line
}
if not line:
break
file_out.write(line)
req = Request('POST', apiURL, data=data, headers=headers) # 페이지 header값으로 요청을 하고 text 변환 코드를 전달
# 서버가 가진 클라이언트가 접속할 때 정보로 생성된 Session의 객체를 통해 값을 리턴받는다.
prepared = req.prepare() # 서버와 연결할 1. 준비단계
res = s.send(prepared) # 2. 세션을 통해 연결고리를 만든다. 데이터 변환 코드 전송
# 결과를 리턴받고 출력한다.
res_json = res.json()
try:
translate = res_json["message"]["result"]["translatedText"]
print(str(translate))
file_out.write(str(translate) + "\n")
except:
pass
file_out.close()
file.close()
mydata_res.txt
또 하루가 저물어 가네요
Another day is coming to an end.
그리움도 잠들 시간이죠
It's time to go to sleep.
오늘도 난 혹시나 하는 맘으로
Today, I'm just wondering.
또 그대를 기다려 봤죠
I've been waiting for you again.
오지 않을 걸 알고는 있지만
I know you're not coming.
기다림으로 행복할 수 있죠
You can be happy waiting.
혼자 하는 사랑도 나쁘지 않아요
Love alone isn't bad either.
곁에 있을 때보다 더 소중하니까
I mean more than when I'm around.
그대 떠난 시간 속에 남아
You stay in the time you left.
그 사랑도 할 수 없다면
If you can't do that love,
나는 살지 못해요
I can't live.
시간이 지나 잊혀질 거라면
If it's going to be forgotten over time,
남은 날 동안 더 사랑 할게요
I'll love you more for the rest of the day.
혼자 하는 사랑도 나쁘지 않아요
Love alone isn't bad either.
곁에 있을 때보다 더 소중하니까
I mean more than when I'm around.
그대 떠난 시간 속에 남아
You stay in the time you left.
그 사랑도 할 수 없다면
If you can't do that love,
나는 살지 못해요
I can't live.
막연한 기다림 속에 슬픔을 묻고
In a vague wait, we bury our sorrows.
가끔은 혼잣말로
Sometimes I talk to myself.
난 그대와 얘기 할 수 있죠 oh
I can talk to you. oh
혼자 하는 사랑도 나쁘지 않네요
Love alone isn't bad either.
곁에 있을 때보다 더 소중하니까
I mean more than when I'm around.
다만 내가 두려워지는 건
The only thing I'm afraid of is...
긴 시간을 견디지 못해
I can't stand a long time.
그댈 잊을까봐
I'm afraid I'll forget you.
늦기 전에 꼭 다시 돌아와요
Make sure you come back before it's too late.
'데이터과학자 - 강의 > python' 카테고리의 다른 글
210512 python - Web crawling (0) | 2021.05.12 |
---|---|
210510 python - JSON (0) | 2021.05.10 |
210507 python - built in function, 모듈 활용 (0) | 2021.05.07 |
210506 python - exception, decimal (0) | 2021.05.06 |
210503 python day-12 : file i/o (0) | 2021.05.04 |