欢迎访问宙启技术站
智能推送

在Python中使用Prompt()函数编写一个简单的单词翻译程序。

发布时间:2024-01-02 09:47:48

要编写一个简单的单词翻译程序,我们可以使用Python的input函数来提示用户输入要翻译的单词,并根据输入的单词返回相应的翻译结果。

下面是一个示例程序,可以实现英文单词到法文的简单翻译:

def translate_word(word):
    translations = {
        'hello': 'bonjour',
        'world': 'monde',
        'python': 'python',
        'programming': 'programmation'
    }
    return translations.get(word, "Translation not found")

def main():
    while True:
        word = input("Enter a word to translate (or 'q' to quit): ")
        if word.lower() == 'q':
            break
        translation = translate_word(word.lower())
        print(f"The translation of '{word}' is '{translation}'.")

if __name__ == "__main__":
    main()

在这个程序中,首先定义了一个translate_word函数,它接受一个单词作为输入,并返回这个单词的翻译结果。翻译结果存储在一个字典中,键是英文单词,值是对应的法文单词。

然后,在main函数中使用一个无限循环来获取用户输入的单词,并调用translate_word函数来获取翻译结果。如果用户输入的是字母"q"(不区分大小写),则退出程序。

示例输出如下:

Enter a word to translate (or 'q' to quit): hello
The translation of 'hello' is 'bonjour'.
Enter a word to translate (or 'q' to quit): world
The translation of 'world' is 'monde'.
Enter a word to translate (or 'q' to quit): python
The translation of 'python' is 'python'.
Enter a word to translate (or 'q' to quit): programming
The translation of 'programming' is 'programmation'.
Enter a word to translate (or 'q' to quit): goodbye
The translation of 'goodbye' is 'Translation not found'.
Enter a word to translate (or 'q' to quit): q

这个简单的程序只能提供一些固定的翻译结果,如果需要更复杂的单词翻译功能,可以考虑使用外部的翻译API或数据库。