tran.py
import json
import urllib.parse
import urllib.request
import re
def translate(text, s_lang='', t_lang=''):
DEEPL_TRANSLATE_EP = 'https://api.deepl.com/v2/translate'
headers = {
'Content-Type': 'application/x-www-form-urlencoded; utf-8'
}
params = {
'auth_key': "",#Enter your API key here
'text': text,
'target_lang': t_lang
}
if s_lang != '':
params['source_lang'] = s_lang
req = urllib.request.Request(
DEEPL_TRANSLATE_EP,
method='POST',
data=urllib.parse.urlencode(params).encode('utf-8'),
headers=headers
)
try:
with urllib.request.urlopen(req) as res:
res_json = json.loads(res.read().decode('utf-8'))
res_json=res_json["translations"][0]["text"]
return json.dumps(res_json, indent=2, ensure_ascii=False)
except urllib.error.HTTPError as e:
return "Could not get it."
#Added the above
with open('text.txt') as f:
text = f.read()
text=re.sub('\n', ' ', text)
text = translate(text, s_lang='', t_lang='JA')
text=re.sub('\n', ' ', text)
print(text)
Place tran.py and text.txt in the same hierarchy, and enter the English text you want to translate into text.txt.
python tran.py
Run tran.py on.
I tried using the DeepL API in Python
Recommended Posts