開始使用免費開始

使用你類別的功能

你現在已在 Document 類別的 __init__ 方法中加入額外功能,會自動為使用者前處理文字。這個練習中,你將扮演其中一位使用者,親自體會你辛苦成果的好處。

Document 類別(如下所示)已載入到你的環境中(包含你剛加入的更新)。

class Document:
  def __init__(self, text):
    self.text = text
    # pre tokenize the document with non-public tokenize method
    self.tokens = self._tokenize()
    # pre tokenize the document with non-public count_words
    self.word_counts = self._count_words()

  def _tokenize(self):
    return tokenize(self.text)

  # non-public method to tally document's word counts with Counter
  def _count_words(self):
    return Counter(self.tokens)

本練習屬於課程

Python 的軟體工程原則

檢視課程

練習說明

  • 以已載入環境的 datacamp_tweets 資料集建立新的 Document 實例。datacamp_tweets 物件是一個包含上百則由 DataCamp 與 DataCamp 使用者撰寫推文的單一字串。
  • 列印 datacamp_doc 的前 5 個 tokens
  • 列印由非公開方法 _count_words()Document.__init__ 中自動計算的前 5 個最常見單字。

動手互動練習

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

# create a new document instance from datacamp_tweets
datacamp_doc = ____(____)

# print the first 5 tokens from datacamp_doc
print(____.____[:5])

# print the top 5 most used words in datacamp_doc
print(____.____.most_common(5))
編輯並執行程式碼