每天一句小詩詞
陽明四句:無善無惡心之體,有善有惡意之動,知善知惡是良知,為善去惡是格物,
今天教大家用Python做一個英漢翻譯小字典,輸入英文,回傳對應中文,
二、知識點
- 檔案讀寫
- 基礎語法
- 例外處理
- 回圈陳述句
- 字串處理
三、代碼展示
匯入模塊
import platform # 我還給大家準備了這些資料:Python視頻教程、100本Python電子書、基礎、爬蟲、資料分析、web開發、機器學習、人工智能、面試題、Python學習路線圖、問題解答! # 都放在這個扣群啦:279199867
英漢字典
eng_hans_dict = {} with open("py014.txt", encoding="utf8") as fin: # 讀取檔案,保存翻譯資料 for line in fin: if len(line.strip()) > 3: eng, hans = line.strip().split(",") eng_hans_dict[eng] = hans print("英漢字典資料: %s -> %s" % (eng, hans))
翻譯
def translate(input_word): try: return eng_hans_dict[input_word] except KeyError: return "單詞不在詞典中"
列印結果
input_word = input("請輸入要翻譯的英文單詞: ").lower() trans_result = translate(input_word) print("%s 的翻譯結果是: %s" % (input_word, trans_result))
全部代碼
import platform print("無善無惡心之體,有善有惡意之動,知善知惡是良知,為善去惡是格物") print("實戰場景: 如何實作一個英漢翻譯小字典 ") eng_hans_dict = {} with open("py014.txt", encoding="utf8") as fin: for line in fin: if len(line.strip()) > 3: eng, hans = line.strip().split(",") eng_hans_dict[eng] = hans print("英漢字典資料: %s -> %s" % (eng, hans)) def translate(input_word): try: return eng_hans_dict[input_word] except KeyError: return "單詞不在詞典中" input_word = input("請輸入要翻譯的英文單詞: ").lower() trans_result = translate(input_word) print("%s 的翻譯結果是: %s" % (input_word, trans_result)) print("Python 版本", platform.python_version())
四、運行結果
無善無惡心之體,有善有惡意之動,知善知惡是良知,為善去惡是格物
實戰場景: 如何實作一個英漢翻譯小字典
英漢字典資料: apple -> 蘋果
英漢字典資料: banana -> 香蕉
英漢字典資料: blueberry -> 藍莓
英漢字典資料: cherry -> 櫻桃
英漢字典資料: crabapple -> 海棠果
英漢字典資料: carambola -> 楊桃
英漢字典資料: chestnut -> 栗子
英漢字典資料: coconut -> 椰子
英漢字典資料: cranberry -> 曼越莓
英漢字典資料: cumquat -> 金桔
英漢字典資料: orange -> 桔子
英漢字典資料: pear -> 梨
英漢字典資料: peach -> 桃
英漢字典資料: grape -> 葡萄
英漢字典資料: lemon -> 檸檬
英漢字典資料: lichee -> 荔枝
英漢字典資料: loquat -> 枇杷
英漢字典資料: mango -> 芒果
請輸入要翻譯的英文單詞: apple
apple 的翻譯結果是: 蘋果
Python 版本 3.10.4
兄弟們,今天的分享就到這,再見!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/500098.html
標籤:其他
上一篇:Python Json使用
