開始使用免費開始

貓出現的次數

你正在進行一個自然語言處理專案,想找出偉大作家之所以偉大的原因。你目前的假設是:偉大的作家「非常常」談到貓。為了驗證這點,你想計算「cat」這個字在 Lewis Carroll 的作品「Alice's Adventures in Wonderland」中出現了多少次。你已經下載了整本書內容的文字檔 alice.txt

本練習屬於課程

Python 函式寫作

檢視課程

練習說明

  • 使用 open() 情境管理器開啟 alice.txt,並把檔案指定給變數 file

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Open "alice.txt" and assign the file to "file"
____ ____('alice.txt') ____ file:
  text = file.read()

n = 0
for word in text.split():
  if word.lower() in ['cat', 'cats']:
    n += 1

print('Lewis Carroll uses the word "cat" {} times'.format(n))
編輯並執行程式碼