4.5 פרויקט תוכנת תרגום פתרון

  • main.py
    from dictionary import handle_dictionary  
    
    
    def print_help_message() -> None:  
        print("Welcome to the dictionary!\n"  
              "what do you want to do today?\n"  
              "1. translate a sentence\n"  
              "2. add a new word translation\n"  
              "3. list all translation\n"  
              "\n")  
    
    
    def main() -> None:  
        print_help_message()  
        handle_dictionary()  
    
    
    if __name__ == '__main__':  
        main()
    
  • dictionary.py
    from actions import actions, valid_actions  
    
    
    def handle_dictionary() -> None:  
        while True:  
            action = get_action()  
            handle_action(action)  
    
    
    def handle_action(action: str) -> None:  
        actions[action]()  
    
    
    def get_action() -> str:  
        while True:  
            action = input("choose action: ")  
            if validate_action(action):  
                return action  
            else:  
                print(f"Invalid action! please enter an action between {valid_actions}\n")  
    
    
    def validate_action(action: str) -> bool:  
        return action in valid_actions
    
  • action.py
    def translate() -> None:  
        sentence = input("enter a sentence to translate: ")  
        translated_list = []  
    
        words = sentence.split()  
        for word in words:  
            translated_list.append(translate_word(word))  
    
        translated_sentence = " ".join(translated_list)  
        print(f"translation: {translated_sentence}\n")  
    
    
    def translate_word(word: str) -> str:  
        with open("dictionary.txt", "r") as file:  
            content = file.read()  
            translations = content.split("\n")[:-1]  
            for translation in translations:  
                origin_word, translated_word = translation.split(" -> ")  
                if origin_word == word:  
                    return translated_word  
    
    
    def add_word() -> None:  
        word = input("enter a word: ")  
        translation = input("enter translation: ")  
    
        with open("dictionary.txt", "a") as file:  
            sentence = f"{word} -> {translation}"  
            file.write(f"{sentence}\n")  
            print(f"added translation {sentence} to dictionary!\n")  
    
    
    def list_all() -> None:  
        with open("dictionary.txt", "r") as file:  
            print("dictionary:\n"  
                  f"{file.read()}\n")  
    
    
    actions = {  
        "1": translate,  
        "2": add_word,  
        "3": list_all  
    }  
    valid_actions = actions.keys()
    
  • dictionary.txt