|
import requests |
|
import json |
|
|
|
def translate_text(text, target_lang='ja', source_lang='en'): |
|
api_key = "AIzaSyAEzK5_n6zKTimD9yoXS-C8O0xN_4LaVBQ" |
|
|
|
text = text.replace('\n', '<br>') |
|
url = f"https://translation.googleapis.com/language/translate/v2?key={api_key}" |
|
payload = { |
|
'q': text, |
|
'source': source_lang, |
|
'target': target_lang, |
|
'format': 'html' |
|
} |
|
headers = { |
|
'Content-Type': 'application/json' |
|
} |
|
|
|
response = requests.post(url, headers=headers, json=payload) |
|
if response.status_code == 200: |
|
translated_text = json.loads(response.text)['data']['translations'][0]['translatedText'] |
|
|
|
translated_text = translated_text.replace('<br>', '\n') |
|
|
|
|
|
translated_text = translated_text.replace("##選択肢【正解選択肢】", "##選択肢\n【正解選択肢】") |
|
|
|
return translated_text |
|
else: |
|
return "Error: " + response.text |