Update translate.py
Browse files- translate.py +8 -3
translate.py
CHANGED
@@ -1,14 +1,16 @@
|
|
1 |
import requests
|
2 |
import json
|
3 |
|
4 |
-
def translate_text(text, target_lang='
|
5 |
api_key = "AIzaSyAEzK5_n6zKTimD9yoXS-C8O0xN_4LaVBQ"
|
|
|
|
|
6 |
url = f"https://translation.googleapis.com/language/translate/v2?key={api_key}"
|
7 |
payload = {
|
8 |
'q': text,
|
9 |
'source': source_lang,
|
10 |
'target': target_lang,
|
11 |
-
'format': '
|
12 |
}
|
13 |
headers = {
|
14 |
'Content-Type': 'application/json'
|
@@ -16,7 +18,10 @@ def translate_text(text, target_lang='ja', source_lang='en'):
|
|
16 |
|
17 |
response = requests.post(url, headers=headers, json=payload)
|
18 |
if response.status_code == 200:
|
19 |
-
|
|
|
|
|
|
|
20 |
else:
|
21 |
return "Error: " + response.text
|
22 |
|
|
|
1 |
import requests
|
2 |
import json
|
3 |
|
4 |
+
def translate_text(text, target_lang='en', source_lang='ja'):
|
5 |
api_key = "AIzaSyAEzK5_n6zKTimD9yoXS-C8O0xN_4LaVBQ"
|
6 |
+
# 元の改行を `<br>` で置き換え
|
7 |
+
text = text.replace('\n', '<br>')
|
8 |
url = f"https://translation.googleapis.com/language/translate/v2?key={api_key}"
|
9 |
payload = {
|
10 |
'q': text,
|
11 |
'source': source_lang,
|
12 |
'target': target_lang,
|
13 |
+
'format': 'html' # フォーマットを 'html' に変更
|
14 |
}
|
15 |
headers = {
|
16 |
'Content-Type': 'application/json'
|
|
|
18 |
|
19 |
response = requests.post(url, headers=headers, json=payload)
|
20 |
if response.status_code == 200:
|
21 |
+
translated_text = json.loads(response.text)['data']['translations'][0]['translatedText']
|
22 |
+
# 翻訳されたテキストの `<br>` を改行に戻す
|
23 |
+
translated_text = translated_text.replace('<br>', '\n')
|
24 |
+
return translated_text
|
25 |
else:
|
26 |
return "Error: " + response.text
|
27 |
|