create a python application that use a language parameter and a file containing all the adjectives and adverbs in English . the application repeatedly choose randomly an English word from the file and ask the translation into the other language. it checks the correctness of the answer and assign one point. when the application ends it returns the statistic of the answers.
Assistant
Certainly! Below is a Python application that fulfills your requirements. This script:
Accepts a target language code as a parameter (e.g., 'fr' for French, 'es' for Spanish).
Reads all adjectives and adverbs from a provided text file.
Randomly selects words and quizzes the user on their translations into the target language.
Checks the correctness of the user's answers.
Keeps track of the user's score.
Provides statistics at the end of the quiz.
python
import argparse
import random
import sys
from googletrans import Translator
def load_words_from_file(filename):
"""Load words from a file and return a list of words."""
try:
with open(filename, 'r', encoding='utf-8') as f:
words = [line.strip() for line in f if line.strip()]
return words
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
sys.exit(1)
def main():
# Set up command-line argument parsing
parser = argparse.ArgumentParser(description='Language translation quiz application.')
parser.add_argument('language', help='Target language code (e.g., "fr" for French, "es" for Spanish).')
parser.add_argument('words_file', help='File containing all adjectives and adverbs in English.')
args = parser.parse_args()
target_language = args.language
words_file = args.words_file
# Load words from the provided file
words = load_words_from_file(words_file)
# Initialize the translator
translator = Translator()
score = 0
total_questions = 0
print("\nWelcome to the Language Translation Quiz!")
print("Type 'exit' at any time to quit.\n")
while True:
# Randomly select a word from the list
word = random.choice(words)
# Attempt to translate the word into the target language
try:
translation = translator.translate(word, dest=target_language).text.lower()
except Exception as e:
print(f"Error translating word '{word}': {e}")
continue
# Prompt the user for a translation
user_input = input(f"Translate '{word}' into {target_language}: ").strip().lower()
# Check if the user wants to exit
if user_input == 'exit':
break
total_questions += 1
# Check the user's answer
if user_input == translation:
print("Correct!\n")
score += 1
else:
print(f"Incorrect. The correct translation is '{translation}'.\n")
# Display quiz statistics
print("\nQuiz ended.")
print(f"Total questions answered: {total_questions}")
print(f"Correct answers: {score}")
if total_questions > 0:
accuracy = (score / total_questions) * 100
print(f"Accuracy: {accuracy:.2f}%\n")
else:
print("No questions were answered.\n")
if __name__ == '__main__':
main()
Instructions to Use the Application:
Install Required Libraries:
Make sure you have the googletrans library installed. You can install it using pip:
bash
pip install googletrans==4.0.0-rc1
Note: As of the time of writing, the stable version of googletrans might have issues due to changes in Google's API. Using the release candidate 4.0.0-rc1 is recommended.
Prepare the Words File:
Create a text file (e.g., adjectives_adverbs.txt) containing all the adjectives and adverbs you wish to include. Each word should be on a separate line. For example:
code
beautiful
quickly
happy
sad
angrily
slowly
red
blue
smart
tall
short
Run the Application:
Execute the script from the command line, providing the target language code and the path to your words file. For example, to translate into French:
bash
python script.py fr adjectives_adverbs.txt
Replace script.py with the name you saved the script as, fr with your desired language code, and adjectives_adverbs.txt with the path to your words file.
Taking the Quiz:
The application will repeatedly prompt you to translate randomly selected words.
Type your translation and press Enter.
To exit the quiz at any time, type exit and press Enter.
Understanding the Output:
After exiting, the application will display the total number of questions answered, the number of correct answers, and your accuracy percentage.
Example Session:
code
Welcome to the Language Translation Quiz!
Type 'exit' at any time to quit.
Translate 'happy' into fr: content
Correct!
Translate 'slowly' into fr: lentement
Correct!
Translate 'smart' into fr: intelligent
Correct!
Translate 'red' into fr: exit
Quiz ended.
Total questions answered: 3
Correct answers: 3
Accuracy: 100.00%
Notes:
Language Codes: Use ISO 639-1 language codes for the target language (e.g., 'fr' for French, 'es' for Spanish, 'de' for German).
Limitations: Machine translations may not always align perfectly with expected answers, especially due to synonyms or contextual differences. This basic implementation checks for exact matches. For a more robust application, consider implementing synonym checks or integrating a more sophisticated language processing library.
Error Handling: The script includes basic error handling for file loading and translation requests. Ensure you have an active internet connection for the translations to work.
Feel free to customize and expand upon this script to better suit your needs!