クラスの機能を使ってみましょう
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で学ぶSoftware Engineeringの原則
演習の手順
- 環境に読み込まれている
datacamp_tweetsデータセットから、新しいDocumentインスタンスを作成します。datacamp_tweetsは、DataCamp とそのユーザーによる何百ものツイートを含む1つの長い文字列です。 datacamp_docのtokensを先頭から5件表示します。Document.__init__メソッド内で非公開メソッド_count_words()により自動計算された、最も出現頻度の高い単語トップ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))