EDIT: DeepL Python Library
I was unaware of this before, but DeepL has a python package that can be used to make text and document translations far more easily than through the requests
package. Some of this is recycled from the DeepL documentation, but updated to answer your question.
First, run a simple pip install deepl
.
If you don't care about hard coding your auth_key, you can set it up like so:
import deepl
translator = deepl.Translator("auth_key")
To translate a single string you can do this:
import deepl
result = translator.translate_text("Che bellissima giornata", target_lang="EN-US")
print(result)
You can now also pass multiple strings in a DeepL request by putting the strings in a list:
import deepl
result = translator.translate_text(["お元気ですか?", "Che bellissima giornata"], target_lang="EN-US")
print(result[0].text) # "How are you?"
print(result[0].detected_source_lang) # "JA"
print(result[1].text) # "What a beautiful day"
print(result[1].detected_source_lang) # "IT"
If you have full foreign language documents you would like to translate you can make a request using the DeepL package as well:
translator.translate_document_from_filepath(
"path/to/write/to/WhatABeautifulDay.docx", # Translated File
"path/to/original/CheBellissimaGiornata.docx", # Original File
target_lang="EN-US"
)
Just as a side note, the DeepL "EN" option is deprecated, and you must now use "EN-US" or "EN-GB" in your request.
OUTDATED (Still Works for Text)
In order to get a correct response, you need to structure your query as such:
import requests
r = requests.post(
url="https://api.deepl.com/v2/translate",
data={
"target_lang": "EN",
"auth_key": auth_key,
"text": string_to_translate,
},
)
Where auth_key
is your authentication key and string_to_translate
is the text you want to translate.
I formatted the above code using black, which is why it looks different than what dwightkschruteIII included, though it is essentially doing the same thing.
To access this translation using python, however, you need to use the following code:
r.json()["translations"][0]["text"]
Because DeepL will return a json with translations
as its only key, with a list containing another json as the corresponding value. The json within the list has two keys: detected_source_language
and text
. This was a verbose explanation, so I've provided a sample below:
The commands:
sample = requests.post(url="https://api.deepl.com/v2/translate", data={"target_lang": "EN", "auth_key": auth_key, "text": "Che bellissima giornata"})
print(sample.json())
Return:
{'translations': [{'detected_source_language': 'IT', 'text': 'What a beautiful day'}]}
So to reiterate, you must use sample.json()["translations"][0]["text"]
to access the translation, where sample is whatever you named your response, and the first code block to get a successful request.