使用你類別的功能
你現在已在 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))