Text Translator in Python
About the project: This is a project for a Text Translator using Python. This project will use a popular library called googletrans to translate text between different languages.
To keep the project self-contained and easy to run, the code will be a single Python file that handles the user input, performs the translation, and displays the result.
This project requires the googletrans library. You can install it by running the following command in your terminal:
pip install googletrans==4.0.0-rc1
Once installed, you can save the code as text_translator.py and run it from the command line:
python text_translator.py
The Canvas provides a functional text translation tool, allowing you to easily convert text from one language to another.
The code includes a simplified list of languages for demonstration purposes.
If you want to support more languages, you would need to expand the language_map dictionary or implement a more robust language code lookup.
Project Level: Intermediate
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE).
# text_translator.py
# Import the Translator class from the googletrans library
# You might need to install it first: pip install googletrans==4.0.0-rc1
from googletrans import Translator
def get_language_code(prompt_message):
"""
Prompts the user for a language name and returns its two-letter code.
This is a simplified approach and may not cover all languages.
"""
# A simplified dictionary for common languages
language_map = {
"english": "en",
"spanish": "es",
"french": "fr",
"german": "de",
"italian": "it",
"japanese": "ja",
"korean": "ko",
"chinese": "zh-CN",
"russian": "ru",
"arabic": "ar",
"portuguese": "pt",
"hindi": "hi",
}
while True:
language = input(prompt_message).strip().lower()
if language in language_map:
return language_map[language]
else:
print(f"'{language}' is not a recognized language or is not supported in this simplified list.")
print("Please choose from:", ', '.join(language_map.keys()))
def main():
"""
Main function to run the Text Translator.
"""
print("--- Python Text Translator ---")
print("This translator uses the Google Translate API.")
translator = Translator()
while True:
print("\nSelect an option:")
print("1. Translate text")
print("2. Quit")
choice = input("Enter your choice (1 or 2): ").strip()
if choice == '2':
print("Exiting Text Translator. Goodbye!")
break
elif choice == '1':
try:
# Get the text to be translated
text_to_translate = input("\nEnter the text you want to translate: ").strip()
if not text_to_translate:
print("Text cannot be empty. Please try again.")
continue
# Get the source language (optional)
source_language_code = input("Enter the source language (e.g., 'english', leave blank for auto-detect): ").strip().lower()
# Get the destination language
dest_language_code = get_language_code("Enter the destination language (e.g., 'spanish'): ")
# Perform the translation
if source_language_code:
translation = translator.translate(text_to_translate, src=source_language_code, dest=dest_language_code)
else:
translation = translator.translate(text_to_translate, dest=dest_language_code)
# Display the result
print("\n--- Translation Result ---")
print(f"Original Text: {translation.origin}")
print(f"Source Language: {translation.src}")
print(f"Translated Text: {translation.text}")
print("--------------------------\n")
except Exception as e:
print(f"An error occurred during translation: {e}")
print("Please check your internet connection and make sure the 'googletrans' library is installed correctly.")
else:
print("Invalid choice. Please enter '1' or '2'.")
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
main()
← Back to Projects