子クラスを使ってみましょう
継承の力のおかげで、親クラスの 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_analyzerをimportします。 - 事前に読み込まれている
datacamp_tweetsオブジェクトをtextに渡し、SocialMediaのインスタンスとしてdc_tweetsを定義します。 - 適切な
dc_tweetsの属性を使って、データ中でメンションされたユーザーのうち5件のmost_commonをprintします。 - 適切な
dc_tweetsの属性を使って、text_analyzerのplot_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.____)