1. Lära sig
  2. /
  3. Courses
  4. /
  5. Pythonで学ぶSoftware Engineeringの原則

Connected

exercise

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

継承の力のおかげで、親クラスの 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='@')

Instruktioner

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