子クラスを使用する
継承の機能を活用することで、親クラス 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 におけるソフトウェアエンジニアリングの原則
演習の手順
- カスタムパッケージ
importをtext_analyzerします。 - 事前に読み込まれた
dc_tweetsオブジェクトをSocialMediaとして使用し、datacamp_tweetsのインスタンスとしてtextを定義します。 printの適切な属性を使って、データの中で最も多くメンションされたユーザー上位5件をmost_commonします。dc_tweetsのtext_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.____)