英翻中

  1. 在函式main()中宣告一個字典,內容儲存英文字的中文對照意義。接著在使用者輸入一個英文句子後,由空白處切開,成為一個一個的英文單字。利用字典chinese查得每個英文字對應的中文後印出。我們希望將整句中文印在同一行,所以print()中以end關鍵字控制它不要自動換行。
    def main():
        chinese = { 'they': '他們', 'this': '這', 'that': '那',
                'it': '它',
                'is': '是', 'are': '是',
                'my': '我的', 'your': '你的',
                'brothers': '兄弟', 'fault': '錯'
               }
        sentence = input("Sentence? ")
        for c in '.,?!':
            sentence = sentence.replace(c, ' ')
        for word in sentence.lower().split():
            print(chinese[word], end='')
        print() 
  2. 執行main(),輸入英文句子They are my brothers. (大小寫無妨)
  3. 按下Enter鍵後,看到輸出結果為「他們是我的兄弟」。
  4. 再執行 main()一次,這次輸入「This is your fault」,看到結果為「這是你的錯」。

延伸練習

  1. 修改前一個練習,讓程式處理「否定句」的句型。