1. 学ぶ
  2. /
  3. コース
  4. /
  5. Pythonで学ぶSoftware Engineeringの原則

Connected

演習

クラスの機能を使ってみましょう

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)

指示

100 XP
  • 環境に読み込まれている datacamp_tweets データセットから、新しい Document インスタンスを作成します。 datacamp_tweets は、DataCamp とそのユーザーによる何百ものツイートを含む1つの長い文字列です。
  • datacamp_doc の tokens を先頭から5件表示します。
  • Document.__init__ メソッド内で非公開メソッド _count_words() により自動計算された、最も出現頻度の高い単語トップ5を表示します。