始める無料で始める

子クラスを使ってみましょう

継承の力のおかげで、親クラスの Document を基に、機能が豊富な SocialMedia クラスを作成できました。これらの機能の一部を実際に見てみましょう。

参考として、以下に 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で学ぶSoftware Engineeringの原則

コースを見る

演習の手順

  • カスタムパッケージ text_analyzerimport します。
  • 事前に読み込まれている datacamp_tweets オブジェクトを text に渡し、SocialMedia のインスタンスとして dc_tweets を定義します。
  • 適切な dc_tweets の属性を使って、データ中でメンションされたユーザーのうち 5 件の most_commonprint します。
  • 適切な dc_tweets の属性を使って、text_analyzerplot_counter() メソッドでデータ中で最も使われているハッシュタグをプロットします。

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

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

# 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.____)
コードを編集して実行