Created
June 16, 2021 04:55
-
-
Save shootacean/82f05c604bc6a27cebea870e3ac41b8e to your computer and use it in GitHub Desktop.
DeepL API Freeを使った日本語ブログ記事タイトルをブログURLに変換するPythonスクリプト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys7 | |
import urllib.request | |
import json | |
DEEPL_AUTH_KEY = "key" #ここをAPIキーで置き換える | |
DEEPL_ENDPOINT_TRANSLATE = "https://api-free.deepl.com/v2/translate" | |
DEEPL_ENDPOINT_USAGE = "https://api-free.deepl.com/v2/usage" | |
def monitor_usage(): | |
"""使用状況を確認する""" | |
headers = { | |
'Content-Type': 'application/x-www-form-urlencoded; utf-8' | |
} | |
params = { | |
'auth_key': DEEPL_AUTH_KEY | |
} | |
req = urllib.request.Request( | |
DEEPL_ENDPOINT_USAGE, | |
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')) | |
return res_json | |
except urllib.error.HTTPError as e: | |
print(e) | |
def translate(text, s_lang='', t_lang='EN'): | |
"""DeepLで翻訳する""" | |
headers = { | |
'Content-Type': 'application/x-www-form-urlencoded; utf-8' | |
} | |
params = { | |
'auth_key': DEEPL_AUTH_KEY, | |
'text': text, | |
'target_lang': t_lang | |
} | |
if s_lang != '': | |
params['source_lang'] = s_lang | |
req = urllib.request.Request( | |
DEEPL_ENDPOINT_TRANSLATE, | |
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')) | |
except urllib.error.HTTPError as e: | |
print(e) | |
return res_json["translations"][0]["text"] | |
def convert(title: str) -> str: | |
"""英文を記事URLの形式に変換する""" | |
newTitle = title.lower() | |
newTitle = newTitle.replace("/", "-", -1) | |
newTitle = newTitle.replace(" ", "-", -1) | |
newTitle = newTitle.replace("'", "", -1) | |
# 他に変換したい文字がある場合は、ここに追記していく | |
# newTitle = newTitle.replace("変換前の文字", "変換後の文字", -1) | |
return newTitle | |
if __name__ == "__main__": | |
usage = monitor_usage() | |
if usage["character_limit"] < usage["character_count"]: | |
print("DeepLのリミットを超えています") | |
sys.exit() | |
# コマンドライン引数を受け取る ( sys.argv[0]はプログラム名なので使用しない ) | |
if (len(sys.argv) == 2): | |
# 引数が1つの場合は、そのまま使用する | |
title = sys.argv[1] | |
else: | |
# 引数が2つ以上の場合は、文字列として連結する | |
title = " ".join(sys.argv[1:]) | |
print(convert(translate(title))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment