1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonでDeepLを使う (論文翻訳用)

Posted at
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': "",#ここにAPIキーを入力
        '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 "取得できませんでした。"
#以上を追加した


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)

使い方

tran.pyとtext.txtを同じ階層に配置し、text.txtに翻訳したい英文を入力して

python tran.py

でtran.pyを実行します。

参考

Python で DeepL API を使ってみた

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?