DeepL Video and Project
Here is how to use the DeepL API to translate text with Python. Please note that even though DeepL has a free plan, you may be required to provide your credit card details.
Project to practice the above code:
Project Description
Create a Python program that can translate text from English to another language using the DeepL API and then let the user save the translated text in a text file.
Before You Start Coding
As you may already know, the DeepL API can be accessed through the following URL endpoint:
https://api-free.deepl.com/v2/translate
How the Project Works
(1) The program prompts the user to enter some text to translate. The user enters the text (e.g., "I hope we get some rain today" (2) The program prompts the user to enter the language code (e.g., IT). (3) The program prints out the translated text. (4) The program asks the user if they want to save the translated text to a file. (5) If the user enters "yes", the program asks the user to type in the name that the file should have (e.g., translation.txt) (6) The program creates the text file and prints out a message that the text was saved in the file.
Suggested Libraries
requests
Installation:
pip install requests
Project Solution
How to run the code
Install the required library by running this in the terminal:
pip install requests
Replace the
api_key
value with your own DeepL API key if you have one. If you don't have one, you can sign up for an API key.Run the code normally in your Python environment.
Output
The code will prompt the user to input text and select a target language for translation. It will then send a request to the DeepL API to translate the text. The translated text will be displayed in the terminal. The user will also have the option to save the translated text to a file.
Code
import requests
# Get user inputs
text_to_translate = input("Enter text: ")
target_language = input("Enter target language (e.g., IT for Italian): ")
# DeepL API URL and API key
url = "https://api-free.deepl.com/v2/translate"
api_key = '5b214a2b-4906-42ea-bdb3-862026badf48:fx'
# Parameters for the API request
params = {
'auth_key': api_key,
'text': text_to_translate,
'target_lang': target_language
}
# Send the request and get the response
response = requests.get(url, data=params)
result = response.json()
# Extract the translated text
translated_text = result['translations'][0]['text']
print("Translated text:", translated_text)
# Ask the user if they want to save the translated text to a file
save_option = input("Do you want to save the translated text to a file? (yes/no): ").strip().lower()
if save_option == 'yes':
file_name = input("Enter the file name (e.g., translation.txt): ").strip()
with open(file_name, 'w') as file:
file.write(translated_text)
print(f"Translated text saved to {file_name}.")
else:
print("Translated text not saved.")