始める無料で始める

クラスの機能を使用する

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 におけるソフトウェアエンジニアリングの原則

コースを見る

演習の手順

  • 環境に読み込まれている Document データセットから、新しい datacamp_tweets インスタンスを作成してください。datacamp_tweets は、DataCamp およびそのユーザーが投稿した数百件のツイートを含む1つの文字列です。
  • tokens から最初の5つの datacamp_doc を出力してください。
  • _count_words() メソッド内で non-public メソッド 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))
コードを編集して実行