始める無料で始める

子クラスを使用する

継承の機能を活用することで、親クラス SocialMedia をもとに多機能な Document クラスを作成できました。実際にその機能を試してみましょう。

以下に SocialMedia の完全な定義を参照用に示します。また、使いやすくするために SocialMedia__init__.py に追加されています。

class SocialMedia(Document):
    def __init__(self, text):
        Document.__init__(self, text)
        self.hashtag_counts = self._count_hashtags()
        self.mention_counts = self._count_mentions()

    def _count_hashtags(self):
        # Filter attribute so only words starting with '#' remain
        return filter_word_counts(self.word_counts, first_char='#')      

    def _count_mentions(self):
        # Filter attribute so only words starting with '@' remain
        return filter_word_counts(self.word_counts, first_char='@')

この演習はコースの一部です

Python におけるソフトウェアエンジニアリングの原則

コースを見る

演習の手順

  • カスタムパッケージ importtext_analyzer します。
  • 事前に読み込まれた dc_tweets オブジェクトを SocialMedia として使用し、datacamp_tweets のインスタンスとして text を定義します。
  • print の適切な属性を使って、データの中で最も多くメンションされたユーザー上位 5 件を most_common します。
  • dc_tweetstext_analyzer メソッドと plot_counter() の適切な属性dc_tweetsを使って、データで最も多く使われたハッシュタグをプロットします。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# Import custom text_analyzer package
import ____

# Create a SocialMedia instance with datacamp_tweets
dc_tweets = ____(text=datacamp_tweets)

# Print the top five most mentioned users
print(dc_tweets.____.most_common(5))

# Plot the most used hashtags
text_analyzer.____(dc_tweets.____)
コードを編集して実行